您的位置:首页 > 其它

[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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: