您的位置:首页 > 其它

LeetCode题解:Linked List Cycle

2016-03-04 09:02 381 查看
/**

* 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) {

if(head==null) return false;

ListNode walker = head;

ListNode runner = head;

while(runner.next!=null && runner.next.next!=null) {

walker = walker.next;

runner = runner.next.next;

if(walker==runner) return true;

}

return false;

}

}

题意:判断链表是否有环

解题思路:快慢指针,若存在环,两指针必定相遇

代码:

/**
* 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) {
if(head==null) return false;
ListNode walker = head;
ListNode runner = head;
while(runner.next!=null && runner.next.next!=null) {
walker = walker.next;
runner = runner.next.next;
if(walker==runner) return true;
}
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: