【链表5】两个链表的第一个公共结点

来源:互联网 发布:jre for windows.exe 编辑:程序博客网 时间:2024/06/14 11:11

题目描述

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

如:链表1:1>>>2>>>3>>

6>>>7     

链表2: 4>>>5>>

  两个链表公共结点为6.如何获取?先让链表走一步(即长链表比短链表多的部分),这时长链表指针在2位置,短链表在4位置。

然后一起走,碰到第一个相等的数(6),即为第一个公共结点。

/*public class ListNode {    int val;    ListNode next = null;    ListNode(int val) {        this.val = val;    }}*/public class Solution {    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {         if(pHead1==null || pHead2==null)            return null;                ListNode commonNode =null;        int len1 = getListNodeLength(pHead1);        int len2 = getListNodeLength(pHead2);                //1 获取两个链表长度的差值        int dif = len1-len2;        ListNode longIndex=pHead1;        ListNode shortIndex=pHead2;                if(dif < 0){            longIndex=pHead2;            shortIndex=pHead1;            dif = -dif;        }                //2 让长的链表指针先走多的dif步        for(int i=0;i<dif;i++){            longIndex = longIndex.next;        }                //3 这时两个链表在同一个位置,同时走,知道碰到相同的值即为第一个公共结点        while(shortIndex != null && longIndex!=null){            if(shortIndex.val == longIndex.val){              commonNode = shortIndex;                return commonNode;            }            longIndex = longIndex.next;            shortIndex = shortIndex.next;        }                return null;            }        //获取链表长度    private static int getListNodeLength(ListNode pHead){        if(pHead == null)            return 0;        int len =0 ;        while(pHead != null){            len++;            pHead = pHead.next;        }        return len;    }        }

方法二:

/*public class ListNode {    int val;    ListNode next = null;    ListNode(int val) {        this.val = val;    }}*/import java.util.*;public class Solution {    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {         if(pHead1 ==  null ||pHead2==null)            return null;        Set<ListNode> set = new HashSet<>();        //先加入链表1 中的结点        while(pHead1 != null){           set.add(pHead1);            pHead1 =  pHead1.next;        }                //同时加入结点2中的元素,如果set.add(pHead2)为false,则代表此元素为两链表公共结点        while(pHead2 != null && set.add(pHead2)){           pHead2 =  pHead2.next;        }        return pHead2;            }}



0 0
原创粉丝点击