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?
题意:判断链表是否成环。
注意:最后一个节点的next指针,有可能指向链表中任意一个节点
方法一:使用HashSet,保存遍历过的节点的HashCode
public class Solution {public bool HasCycle(ListNode head) {if (head == null) {return false;}ListNode node = head;HashSet<int> hashSet = new HashSet<int>();hashSet.Add(node.GetHashCode());while (node.next != null) {node = node.next;int hash = node.GetHashCode();if (hashSet.Contains(hash)) {return true;} else {hashSet.Add(hash);}}return false;}}
方法二:使用两个指针,一个快一个慢,如果两个指针相遇,则链表成环
public class Solution {public bool HasCycle(ListNode head) {if (head == null || head.next == null) {return false;}ListNode slow = head;ListNode fast = head;while (fast.next != null && fast.next.next != null) {slow = slow.next;fast = fast.next.next;if (slow == fast) {return true;}}return false;}}

浙公网安备 33010602011771号