LeetCode: Linked List Cycle解题报告

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?

SOLUTION 1:

  依次将链表节点添加入已知集合,添加前检查该节点是否已经存在于已知集合中。若有,则说明链表带环;若链表所有点均能加入已知集合,则说明链表无环。

加入第 i 个链表节点是查找耗时(i-1),最坏情况时有n个节点加入,即无环。时间复杂度(O(n^2)),空间复杂度为(n)。这个办法简单但是耗时耗空间。

SOLUTION 2:

  指针赛跑,两个指针一快一慢,如果有环会相遇;如果没有环则快的先到达NULL;

  时间复杂度     ;not extra space.

  代码实现的时候要注意边界情况;

 

 1 bool hasCycle(ListNode *head) {
 2         
 3         if (!head) return false;
 4         ListNode *s = head, *f = head->next;
 5         while (f && f->next) {
 6             s = s->next;
 7             f = f->next->next;
 8             if (s == f) return true;
 9         }
10     
11         return false;
12 }
View Code

 

 //reimplement in 2015.03.02
 // case: fast->next is NULL
    bool hasCycle(ListNode *head) {
        if(head){
            ListNode *slow = head;
            ListNode *fast = head->next;
            while(fast && fast->next){
                if(slow == fast){
                    return true;
                }
                slow = slow->next;
                fast = fast->next->next;
            }
        }
        return false;
    }
reimplement in 2015.03.02

 

posted @ 2015-03-11 22:41  伪cnblog_com  阅读(108)  评论(0编辑  收藏  举报