LeetCode#160.Intersection of Two Linked Lists

来源:互联网 发布:量子 知乎 编辑:程序博客网 时间:2024/06/10 11:41
  • 题目:求两个链表相交的起始节点
  • 难度:Easy
  • 思路:(1)求出两个链表的长度,让长的链表先走n步(两个链表长度的差),然后两个链表同时走;(2)如果两个链表相交,经过两趟循环遍历就能找到交点,第一次遍历后,将节点指向另一个链表的头
  • 代码:
    方法一:
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {        if(headA == null || headB == null){            return null;        }        int len1 = 1;        int len2 = 1;        ListNode node1 = headA;        ListNode node2 = headB;        //求出第一个链表的长度        while(node1.next != null){            node1 = node1.next;            len1++;        }        //求出第二个链表的长度        while(node2.next != null){            node2 = node2.next;            len2++;        }        //如果两个链表的尾不相同的话,则说明链表不会相交        if(node1 != node2){            return null;        }        //headA先走len1 - len2步        if(len1 > len2){            for(int i = 0; i < len1 - len2; i++){                headA = headA.next;            }        }else{            for(int i = 0; i < len2 - len1; i++){                headB = headB.next;            }        }        while(headA != headB){            headA = headA.next;            headB = headB.next;        }        return headA;    }

方法二:

public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {        //boundary check        if(headA == null || headB == null) return null;        ListNode a = headA;        ListNode b = headB;        //if a & b have different len, then we will stop the loop after second iteration        while( a != b){            //for the end of first iteration, we just reset the pointer to the head of another linkedlist            a = a == null? headB : a.next;            b = b == null? headA : b.next;        }        return a;    }
0 0
原创粉丝点击