您的位置:首页 > 编程语言 > C语言/C++

Leetcode 141. Linked List Cycle (Easy) (cpp)

2016-07-12 12:47 483 查看
Leetcode 141. Linked List Cycle (Easy) (cpp)

Tag: Linked List, Two Pointers

Difficulty: Easy

/*

141. Linked List Cycle (Easy)

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

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