Leetcode:Linked List Cycle

经典题目:

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

方案一:

 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         if(head==NULL) return false;
13         ListNode* Node = NULL;
14         ListNode* temp = NULL;
15         Node = head;
16         while(head->next!=NULL)
17         {
18             temp = head;
19             head = head->next;
20             temp->next = Node;
21             if(head->next==Node)
22                 return true;
23         }
24         return false;
25     }
26 };

方案二:

 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         // head ==null?
13         if(head==NULL) return false;
14         ListNode *fast = head->next, *slow=head;
15         while(fast!=NULL && fast->next!=NULL)
16         {
17             if(fast==slow)
18                 return true;
19             fast = fast->next->next;
20             slow = slow->next;
21         }
22         return false;
23     }
24 };

建议与易出错地方:

1.在纸上写代码时,开始留些空白,如果需要处理边界情况,可直接加上。

2. 声明指针变量时一定要保持*在变量上的好习惯,否则容易写成 ListNode* fast=head, slow = head; 这就错了!

3. 过程中一个错是  开始初始化直接

 ListNode *fast = head, *slow=head;
后面fast==slow的判断,就直接为真了。

posted on 2014-04-26 14:38  soyscut  阅读(121)  评论(0编辑  收藏  举报

导航