您的位置:首页 > 其它

LeetCode: Linked List Cycle I & II

2017-05-22 20:21 441 查看
推荐参照:Leetcode题目难度等级及面试频率总结

     这是最近我总结的一些关于链表的一些操作合集,包括测试代码

题目描述:Linked List Cycle

  Given a linked list, determine if it has a cycle in it. Can you solve it without using extra space?

思路一:

  设定两个指针slow,fast,其中slow每次向前移动一步(俗称慢指针),fast每次向前移动两步(快指针)。如果单链表存在环,则slow和fast相遇;否则fast将首先遇到null。但是当一个存在环的链表足够长,而环足够小,那么会存在快指针永远不会追上慢指针的情况。

public static boolean hasCycle(ListNode head){
if (head == null || head.next == null)
return false;
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast)
return true;
}
// 释放回收
slow = null;
fast = null;
return false;
}


思路二:

  利用set或者Map存储已经访问过的节点,但是不满足题目要求。

public static boolean isExistCycleListBySet(Node head) {
if (head == null || head.next == null)
return false;
HashSet<Node> set = new HashSet<Node>();
while (head != null) {
if (set.contains(head))
return true;
else {
set.add(head);
head = head.next;
}
}
return false;
}


题目描述:Linked List Cycle II

  Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Can you solve it without using extra space?

思路一:

  首先,找到第一次相遇的位置;然后,slow从链表头出发,fast从第一次相遇的位置出发,再次相遇时即为环开始的地方。

public ListNode detectCycle(ListNode head) {
if(head == null || head.next == null)
return null;
ListNode slow = head;
ListNode fast = head;
boolean hasCycle = false;
while(fast != null && fast.next != null){
// 找到第一次相遇的位置
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
hasCycle = true;
break;
}
}
if(hasCycle){
// slow从链表头出发,fast从第一次相遇的位置出发,再次相遇时即为环开始的地方。
slow = head;
while(slow != fast){
slow = slow.next;
fast = fast.next;
}
fast = null;
return slow;
}else
return null;
}


思路二:

  已知一个单链表中存在环,求进入环中的第一个节点,利用hashmap

public static Node getFirstNodeInCycleHashMap(Node head){
Node target = null;
HashMap<Node, Boolean> map = new HashMap<Node, Boolean>();
while(head != null){
if(map.containsKey(head))
target = head;
else{
map.put(head, true);
}
head = head.next;
}
return target;
}


  Any comments greatly appreciated.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息