本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

LeetCode:Linked List Cycle

题目:判断单链表是否有环,要求O(1)空间复杂度。题目链接

利用快慢指针,开始两个指针均指向链表head,然后循环移动,慢指针移动1步,快指针则移动2步,如果链表有环则两个指针一定会相遇。代码如下:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool hasCycle(ListNode *head) {
12         // IMPORTANT: Please reset any member data you declared, as
13         // the same Solution instance will be reused for each test case.
14         if(head == NULL || head->next == NULL)return false;
15         ListNode *fast = head, *low = head;
16         while(fast != NULL && fast->next != NULL)
17         {
18             low  = low->next;
19             fast = fast->next->next;
20             if(low == fast)return true;
21         }
22         return false;
23     }
24 };

当然还可以用倒转链表的方法来判断是否有环,沿着链表遍历,每次遍历把指针倒转,如果有环最后一定会回到head节点。不过这样会破坏链表结构 ,需要恢复。

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool hasCycle(ListNode *head) {
12         // IMPORTANT: Please reset any member data you declared, as
13         // the same Solution instance will be reused for each test case.
14         if(head == NULL || head->next == NULL)return false;
15         ListNode *p  = head->next, *pre = head;
16         while(p)
17         {
18             if(p == head)return true;
19             ListNode* tmp = p->next;
20             p->next = pre;
21             pre = p;
22             p = tmp;
23         }
24         return false;
25     }
26 };

 

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3416670.html

posted @ 2013-11-10 14:39  tenos  阅读(1298)  评论(0编辑  收藏  举报

本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

公益页面-寻找遗失儿童