您的位置:首页 > 其它

leetcode-141-Linked List Cycle

2015-06-22 22:04 453 查看


Linked List Cycle

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) {  //STL里的set  每插入一个节点 判断是否成功插入
set<ListNode*>s;
int n=0;
while(head){
n++;
s.insert(head);
if(s.size()!=n) return true;  // 没有成功插入 有环
head=head->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) {
if(!head||!head->next) return false;
ListNode* fast=head->next->next;

while(fast!=head){    // 采用快慢指针 fast每次走两步 head走一步 若有环 则必定相遇
if(!fast||!fast->next) return false;

fast=fast->next->next;
head=head->next;
}
return true;
}
};


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
# @param head, a ListNode   # python
# @return a boolean
def hasCycle(self, head):
if not head or not head.next:
return False
fast=head.next.next

while fast!=head:
if not fast or not fast.next:
return False
head=head.next
fast=fast.next.next
return True;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: