【链表5】两个链表的第一个公共结点
来源:互联网 发布:jre for windows.exe 编辑:程序博客网 时间:2024/06/14 11:11
题目描述
输入两个链表,找出它们的第一个公共结点。
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
- 【链表5】两个链表的第一个公共结点
- 链表6:两个链表的第一个公共结点
- 两个链表的第一个公共结点(链表)
- 找出两个链表的第一个公共结点--总结
- 找出两个链表的第一个公共结点
- 找两个链表的第一个公共结点
- 找出两个链表的第一个公共结点
- 找出两个链表的第一个公共结点
- 找出两个链表的第一个公共结点
- 找出两个链表的第一个公共结点
- 找出两个链表的第一个公共结点
- 两个链表的第一个公共结点
- 找出两个链表的第一个公共结点
- 两个链表的第一个公共结点
- 两个链表的第一个公共结点
- 两个链表的第一个公共结点
- 找两个链表的第一个公共结点
- 两个链表的第一个公共结点(剑指offer37)
- Table中合并单元格
- JAVA-编码
- 基于Spring的第一个小应用
- Linux ls -l命令输出详解
- iOS-Main-(RAC演练)-程序架构的搭建
- 【链表5】两个链表的第一个公共结点
- 剑指offer-算法题练习:part17 反转链表
- opencv 资料备份及机器学习
- Oracle 表和表数据恢复
- 梯度下降与线性回归--《机器学习》课程学习笔记
- 斐波那契数列的一种计算方法
- C/C++中结构体占用内存大小的计算方法
- iOS-Main-(RAC演练)-订阅和发送信号
- 最大子序列和问题