(LeetCode 面试经典 150 题) 141. 环形链表(快慢指针)
题目:141. 环形链表
思路:快慢指针,时间复杂度0(n)。
有环的话,最终是会相遇的。也可以使用哈希表来存储遍历过的每个节点信息,但空间复杂度0(n)。
C++版本:
/*** 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 * fast=head,* last=head;while(fast!=nullptr && fast->next !=nullptr){last=last->next;fast=fast->next->next;if(last==fast){return true;}}return false;}
};
JAVA版本:
/*** 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,last=head;while(fast!=null && fast.next!=null){fast=fast.next.next;last=last.next;if(fast==last) return true;}return false;}
}
GO版本:
/*** Definition for singly-linked list.* type ListNode struct {* Val int* Next *ListNode* }*/
func hasCycle(head *ListNode) bool {fast,last:=head,headfor fast!=nil &&fast.Next!=nil {fast=fast.Next.Nextlast=last.Nextif fast==last {return true}}return false
}