您的位置:首页 > 其它

leetcode 141: Linked List Cycle

2015-08-19 14:20 495 查看
Traversal the Linked List, and at the mean time, reverse the direction. If the traversal finally reaches head again, there exists a cycle.

/**
* 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)
return false;
ListNode *curr=head->next,*pre=head;
while(curr)
{
if(curr==head)
return true;
ListNode *temp=curr->next;
curr->next=pre;
pre=curr;
curr=temp;
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: