Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Can you solve it without using extra space?
用最常用的办法,快慢节点各一个,一个走两步,一个走一步.如果快的那个先遇到NULL,证明无环,如果快慢节点相遇,证明有环.关键是要在循环里判断是否到尾端.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 == NULL) return false; | |
if(head->next == NULL) return false; | |
ListNode *p_1, *p_2; | |
p_1 = head; | |
p_2 = head->next; | |
while(p_1!=NULL && p_2!= NULL){ | |
if(p_1 == p_2) return true; | |
p_1 = p_1->next; | |
p_2 = p_2->next; | |
if(p_2 == NULL) | |
return false; | |
else | |
p_2 = p_2->next; | |
} | |
return false; | |
} | |
}; |
No comments:
Post a Comment