剑指Offer—36—两个链表的第一个公共节点

来源:互联网 发布:linux dd备份 编辑:程序博客网 时间:2024/06/09 21:02

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

package A36两个链表的第一个公共节点;public class Solution {    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {        ListNode p1 = pHead1;        ListNode p2 = pHead2;        int lenP1 = getLength(p1);        int lenP2 = getLength(p2);        if (lenP1 > lenP2){            for (int i = 0; i < lenP1-lenP2; i++) {                p1 = p1.next;            }        }else{            for (int i = 0; i < lenP2-lenP1; i++) {                p2 = p2.next;            }        }        while (p1 != p2){            p1 = p1.next;            p2 = p2.next;        }        return p1;    }    public int getLength(ListNode listNode){        if (listNode == null){            return 0;        }        int count = 0;        ListNode cur = listNode;        while (cur != null){            cur = cur.next;            count++;        }        return count;    }}class ListNode {    int val;    ListNode next = null;    ListNode(int val) {        this.val = val;    }}
package A36两个链表的第一个公共节点;public class Solution1 {    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {        // 别人的        ListNode p1 = pHead1;        ListNode p2 = pHead2;        while(p1 != p2){            p1 = ( (p1 == null) ? pHead2 : p1.next);            p2 = ( (p2 == null) ? pHead1 : p2.next);        }        return p1;    }}class ListNode {    int val;    A36两个链表的第一个公共节点.ListNode next = null;    ListNode(int val) {        this.val = val;    }}
阅读全文
0 0