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

来源:互联网 发布:淘宝医药商城 编辑:程序博客网 时间:2024/06/06 17:53

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

思路:①先遍历两个链表得到它们的长度,求出长链表比短链表多几个;②第二次遍历,在长链表上先走若干步,接着同时在两个链表上遍历,找到的第一个相同的结点就是它们的第一个公共结点。

public class ListNode {    int val;    ListNode next = null;    ListNode(int val) {        this.val = val;    }};
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {        if(pHead1 == null || pHead2 == null){    return null;    }    int length1 = getListLength(pHead1);    int length2 = getListLength(pHead2);    ListNode pNodeLong = pHead1;    ListNode pNodeShort = pHead2;    int lengthDif = length1-length2;    if(length2 > length1){    lengthDif = length2-length1;    pNodeLong = pHead2;    pNodeShort = pHead1;    }    //先在长链表上走几步,再同步在两个链表上遍历    for(int i=0;i<lengthDif;i++){   pNodeLong = pNodeLong.next;}    while((pNodeLong != null)&&(pNodeShort != null)&&(pNodeLong != pNodeShort)){    pNodeLong = pNodeLong.next;    pNodeShort = pNodeShort.next;    }    //得到第一个公共结点    ListNode FirstCommonNode = pNodeLong;    return FirstCommonNode;    }        private static int getListLength(ListNode pHead){    if(pHead == null){    return 0;    }    int count = 0;    ListNode pNode = pHead;    while(pNode != null){    count++;    pNode = pNode.next;    }    return count;    }





0 0
原创粉丝点击