链表中环
思路:
1.将ListNode一个个放入set,并检查是否已经存在set中
2.双指针,快慢指针
判断是否有环比较简单,找环的起点浮复杂一些。
#include <iostream> #include <set> using namespace std; struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} }; ListNode* findloop(ListNode* head) { set<ListNode*> set; while(head) { if(set.find(head) != set.end()) return head; set.insert(head); head = head->next; } return NULL; } ListNode* findloop1(ListNode* head) { ListNode* prehead = head; ListNode* fast = prehead; ListNode* slow = prehead; while(fast) { slow = slow->next; fast = fast->next; if(!fast) //至少要走两个节点 return NULL; fast = fast->next; if(slow == fast) break; } cout << fast->val<< endl; cout << slow->val<< endl; if(slow != fast) return NULL; while(1) //一定有环了 { if(slow == prehead) return prehead; prehead = prehead->next; slow = slow->next; } return NULL; } int main() { ListNode l1(7); ListNode l2(8); ListNode l3(9); ListNode a(0); ListNode b(1); ListNode c(2); ListNode d(3); ListNode f(4); ListNode e(5); ListNode g(6); l1.next = &l2; l2.next = &a; l2.next = &a; a.next = &b; b.next = &c; c.next = &d; d.next = &f; f.next = &e; e.next = &a; cout << findloop1(&l1)->val << endl; return 0; }