两个链表的第一个公共节点
来源:互联网 发布:淘宝医药商城 编辑:程序博客网 时间: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
- 两个链表的公共第一个公共节点
- 找到两个单向链表的第一个公共节点
- 找到两个单向链表的第一个公共节点
- 找到两个单向链表的第一个公共节点
- 两个单向链表的第一个公共节点
- 两个链表的第一个公共节点
- 寻找两个相交链表的第一个公共节点
- 两个链表的第一个公共节点
- 寻找两个相交链表的第一个公共节点
- 寻找两个相交链表的第一个公共节点
- 两个链表的第一个公共节点
- 两个链表的第一个公共节点
- 找出两个链表的第一个公共节点
- (LeetCode)两个链表的第一个公共节点
- 37 - 两个链表的第一个公共节点
- 两个链表的第一个公共节点
- 剑指offer-两个链表的第一个公共节点
- 两个链表的第一个公共节点
- 弹性运动框架
- 【GDB调试学习笔记】调试程序段错误
- 矩阵快速幂
- Android Bluetooth(蓝牙)实例
- leetcode 24. Swap Nodes in Pairs
- 两个链表的第一个公共节点
- SGU 223 little kings BSOJ2772 状压DP
- leetcode 167 Two Sum II - Input array is sorted C++
- struts令牌机制
- Java中反射知识的理解介绍
- Scala10
- poj 3348 Cows
- Hive安装
- transaction简介