4.24 leetcode -24 linked-list-cycle
2017-08-29 15:14
344 查看
题目描述
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
给一个链表,看是否有循环,不用额外控件,一个一步走,一个两步走,能汇合就有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) {
ListNode * ponestep = head;
ListNode * ptwostep = head;
if(head == NULL)
return false;
else if(head->next == NULL)
return false;
ptwostep = ptwostep->next;
while(ptwostep!= ponestep && ptwostep->next != NULL && ptwostep->next->next !=NULL)
{
ptwostep =ptwostep->next->next;
ponestep = ponestep->next;
}
if(ptwostep== ponestep)
return true;
else
return false;
}
};
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
给一个链表,看是否有循环,不用额外控件,一个一步走,一个两步走,能汇合就有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) {
ListNode * ponestep = head;
ListNode * ptwostep = head;
if(head == NULL)
return false;
else if(head->next == NULL)
return false;
ptwostep = ptwostep->next;
while(ptwostep!= ponestep && ptwostep->next != NULL && ptwostep->next->next !=NULL)
{
ptwostep =ptwostep->next->next;
ponestep = ponestep->next;
}
if(ptwostep== ponestep)
return true;
else
return false;
}
};
相关文章推荐
- leetcode 之Linked List Cycle(24)
- Leetcode: Linked List Cycle II
- leetcode--Linked List Cycle
- LeetCode - linked-list-cycle-ii
- [Leetcode]#141 Linked List Cycle
- [LeetCode]Linked List Cycle
- LeetCode OJ Linked List Cycle II
- leetcode_Linked List Cycle
- Leetcode: linked-list-cycle-ii
- Leetcode: Linked List Cycle II
- LeetCode: Linked List Cycle
- [LeetCode] Linked List Cycle
- leetcode Linked List Cycle II
- LeetCode 之 Linked List Cycle I II — C++ 实现
- [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- [Leetcode] Linked List Cycle II (Java)
- [leetcode] Linked List Cycle
- LeetCode | Linked List Cycle
- LeetCode142 Linked List Cycle II
- Leetcode-Linked List Cycle II