[LeetCode 第10题] -- Linked List Cycle
2014-12-11 20:57
274 查看
题目链接: linked List 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);
};
bool Solution::hasCycle (ListNode *head) {
if (NULL == head) {
return false;
}
ListNode *tmpHeadOne = head;
ListNode *tmpHeadTwo = head;
int step = 0;
while ((tmpHeadOne != NULL) && (tmpHeadTwo != NULL)) {
if ((step != 0) && (tmpHeadOne == tmpHeadTwo)) {
return true;
}
step++;
tmpHeadOne = tmpHeadOne->next;
tmpHeadTwo = tmpHeadTwo->next;
if (tmpHeadTwo != NULL) {
tmpHeadTwo = tmpHeadTwo->next;
}
}
return false;
}
题目意思: 给定一个链表,判断链表是否有环
代码:
/**
* 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);
};
bool Solution::hasCycle (ListNode *head) {
if (NULL == head) {
return false;
}
ListNode *tmpHeadOne = head;
ListNode *tmpHeadTwo = head;
int step = 0;
while ((tmpHeadOne != NULL) && (tmpHeadTwo != NULL)) {
if ((step != 0) && (tmpHeadOne == tmpHeadTwo)) {
return true;
}
step++;
tmpHeadOne = tmpHeadOne->next;
tmpHeadTwo = tmpHeadTwo->next;
if (tmpHeadTwo != NULL) {
tmpHeadTwo = tmpHeadTwo->next;
}
}
return false;
}
相关文章推荐
- leetcode第10题(linked-list-cycle)
- Leetcode@python Linked List Cycle
- LeetCode Linked List Cycle II
- [LeetCode]Linked List Cycle
- leetcode 141.Linked List Cycle && 142 .Linked List Cycle ii
- LeetCode 142: Linked List Cycle II
- [leetCode]Linked List Cycle I+II
- leetcode-Linked List Cycle II
- 【LeetCode】Linked List Cycle
- LeetCode--linked-list-cycle
- [LeetCode]Linked List Cycle
- Leetcode_linked-list-cycle(c++ and python version)
- leetcode Linked List Cycle
- LeetCode: Linked List Cycle [141]
- [LeetCode] Linked List Cycle II
- LeetCode:142. Linked List Cycle II
- [LeetCode]Linked List Cycle II解法学习
- [LeetCode] - Linked List Cycle II
- 142 Linked List Cycle II [Leetcode]
- LeetCode Linked List Cycle II(找到带环单向链表的环起始位置)