3 - Two Pointers Algorithm

380. Intersection of Two Linked Lists

https://www.lintcode.com/problem/intersection-of-two-linked-lists/description?_from=ladder&&fromId=1

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        // write your code here
        if(headA == null || headB == null) {
            return null;
        }
        ListNode a = headA;
        ListNode b = headB;
        while(a != b) {
            a = a == null ? headB : a.next;
            b = b == null ? headA : b.next;
        }
        return a;
    }

 

102. Linked List Cycle

https://www.lintcode.com/problem/linked-list-cycle/description?_from=ladder&&fromId=1

    public boolean hasCycle(ListNode head) {
        // write your code here
        if(head == null || head.next == null) {
            return false;
        }
        ListNode slow = head, fast = head.next;
        while(slow != fast) {
            if(fast == null || fast.next == null) {
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }

 

posted @ 2019-05-18 12:26  Jenna777  阅读(101)  评论(0编辑  收藏  举报