Day005: linked list cycle

来源:互联网 发布:excel数据统计图表 编辑:程序博客网 时间:2024/06/14 09:16

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

Follow up:
Can you solve it without using extra space?
Difficulty:
1.Without using extra space
2.Because we can’t change List Node structure,so we can’t label node if we visit it or not.
3.Think all of the boundary condition,in case of wrong judgment
Solve:
Set two list node,the faster one’s speed is two time of the lower one,if there has a cycle,the faster one will catch the lower one,else the faster one will be nullptr.

Another Solution:
when we meet a node,we put the node’s next into itself,then if there has a cycle,we will meet a node who’s next is itself.

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    bool hasCycle(ListNode *head) {        if (head == nullptr){            return false;        }        if (head->next==nullptr){            if (head->next==head){                return true;            }            else{                return false;            }        }        ListNode*low = head;        ListNode*fast = head->next;        while(true){            if (fast==low){                return true;            }            if(fast == nullptr){                return false;            }            fast = fast->next;            if (fast == nullptr) return false;            fast = fast->next;            low = low->next;        }    }};
0 0
原创粉丝点击