两个链表的第一个公共结点

来源:互联网 发布:2016年驾校招生数据 编辑:程序博客网 时间:2024/06/11 18:00

输入两个链表,找出它们的第一个公共结点。

//因为最后一个null结点是公共的;所以后面部分就是公共的/*public class ListNode {    int val;    ListNode next = null;    ListNode(int val) {        this.val = val;    }}*/public class Solution {    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {        int len1 = getLength(pHead1);        int len2 = getLength(pHead2);        if (len1 > len2) {            pHead1 = walkStep(pHead1, len1-len2);        } else {            pHead2 = walkStep(pHead2, len2-len1);        }        while (pHead1 != null) {            if (pHead1 == pHead2) return pHead1;            pHead1 = pHead1.next;            pHead2 = pHead2.next;        }        return null;    }    private ListNode walkStep(ListNode pHead, int step) {        while (step != 0) {            pHead = pHead.next;            step--;        }        return pHead;    }    private int getLength(ListNode pHead) {        if (pHead == null) return 0;        int sum = 1;        while (pHead.next != null) {            pHead = pHead.next;            sum++;        }        return sum;    }}
原创粉丝点击