Easy 141题 Linked List Cycle Medium 142题 Linked List Cycle II

来源:互联网 发布:linux test -e 编辑:程序博客网 时间:2024/05/23 00:08

Question:

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

Solution:

/** * 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 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;    }}


Question:

Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.

Note: Do not modify the linked list.


Solution:

/** * Definition for singly-linked list. * class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode detectCycle(ListNode head) {        if(head==null)            return null;        ListNode slow=head;        ListNode fast=head;        ListNode tmp=null;        while(fast.next!=null&&fast.next.next!=null){            slow=slow.next;            fast=fast.next.next;            if(slow==fast){                tmp=slow;                break;            }        }        if(tmp==null)            return null;        //show and fast are the same        slow=tmp;        fast=head;        while(slow!=fast){            slow=slow.next;            fast=fast.next;        }        return slow;                    }}


0 0