LeetCode141LinkedListCycle和142LinkedListCycleII

141题:判断链表是不是存在环!

 1 // 不能使用额外的存储空间
 2     public boolean hasCycle(ListNode head) {
 3         // 如果存在环的 两个指针用不一样的速度 会相遇
 4         ListNode fastNode = head;
 5         ListNode slowNode = head;
 6         while (fastNode != null && fastNode.next != null) {
 7             fastNode = fastNode.next.next;
 8             slowNode = slowNode.next;
 9             if (fastNode == slowNode) {
10                 return true;
11             }
12         }
13         return false;
14     }

142 给定一个链表,返回链表环开始的地方,如果没有环,就返回空。

思路:链表头结点到链表环开始的地方的步数和两个链表相遇的地方到链表开始的地方的步数是一样多的!

 1 // 如果有环,相遇的时候与起点相差的步数等于从head到起点的步数
 2     public ListNode detectCycle(ListNode head) {
 3         ListNode pre = head;
 4         ListNode slow = head;
 5         ListNode fast = head;
 6         while (fast != null && fast.next != null) {
 7             fast = fast.next.next;
 8             slow = slow.next;
 9             if (slow == fast) {
10                 while (pre != slow) {
11                     slow = slow.next;
12                     pre = pre.next;
13                 }
14                 return pre;
15             }
16         }
17         return null;
18     }

猜你喜欢

转载自www.cnblogs.com/ntbww93/p/9103003.html
今日推荐