1. 程式人生 > >[Leetcode]141. Linked List Cycle

[Leetcode]141. Linked List Cycle

bool pan turn code asc lin cnblogs solution false

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

思路:快慢指針,設置一個走兩步的快指針,和一個走一步的慢指針,如果有環,則它們一定會相遇。

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

[Leetcode]141. Linked List Cycle