解题思路: 网上最经典的解法,追击法。设立两个指针,一个指针p加1
一个指针q加2,往链表末端移动。如果q==null,则说明链表没有环,如果
p==q,则说明链表存在环。
核心算法:
- bool HasCycle(Node* head)
- {
- Node* p = head;
- Node* q = head;
- while(true)
- {
- p = p->next;
- q = q->next->next;
- if(q == NULL)
- return false;
- if(p == q)
- return true;
- }
- }
- void AddCycle(Node* head, int n)
- {
- Node* p = head;
- Node* q = head;
- while(p->next)
- p = p->next;
- for(int i = 0; i < n; i++)
- {
- if(i == n-1)
- p->next = q;
- q = q->next;
- if(q == NULL)
- printf("error!/n");
- }
- }
测试的代码:
2009年9月20号
这道题的解法还可以用来解决另外一个问题: 找出单向链表的中间结点