leetcode-141-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?

分析


题意是判断一个链表是否有环,这道题我见过的。。。。
设置前后两个指针,一个指针每次移动两个元素,一个指针每次移动一个,若链表是有环的,两指针最终会相遇,时间复杂度是 $O(n)$

解决方案1(python)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if not head or not head.next:
return False
slow = head
fast = head.next

while slow != fast:
if not fast or not fast.next:
return False
slow = slow.next
fast = fast.next.next
return True

解决方案2(C++)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* 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 == NULL || head->next == NULL) {
return false;
}
ListNode *fast = head;
ListNode *slow = head;

while(slow != NULL && slow->next != NULL) {
slow = slow->next->next;
fast = fast->next;
if(slow == fast) {
return true;
}
}
return false;
}
};

解决方案3(Java)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fast = head, slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
return true;
}
}
return false;
}
}

解决方案4(Golang)


哈希表法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func hasCycle(head *ListNode) bool {
seen := map[*ListNode]int{}

for head != nil {
if _, ok := seen[head]; ok {
return true
}
seen[head] = 1
head = head.Next
}
return false
}

解决方案5(Golang)


快慢指针法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func hasCycle(head *ListNode) bool {
if head == nil || head.Next == nil {
return false
}

slow, fast := head, head.Next
for fast != slow {
if fast == nil || fast.Next == nil {
return false
}
slow = slow.Next
fast = fast.Next.Next
}
return true
}

相关问题


题目来源