剑指Offer_36_两个链表的第一个公共结点
来源:互联网 发布:java 随机数生成 编辑:程序博客网 时间:2024/06/03 20:48
题目描述
输入两个链表,找出它们的第一个公共结点。
解题思路
首先求出两个链表的长度,长的链表先走到和短的链表具有相同长度的位置,然后同时遍历比较两个链表,直到找到相同的结点。
实现
/*链表结点定义*/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; int len1 = getLength(pHead1); int len2 = getLength(pHead2); int gap = 0; ListNode p1,p2; if (len1 > len2) { p1 = pHead1; p2 = pHead2; gap = len1 - len2; }else { p1 = pHead2; p2 = pHead1; gap = len2 - len1; } for (int i = 0; i < gap; i++){ if (p1!= null) p1 = p1.next; } while (p1 != null && p2 != null){ if (p1 == p2) return p1; p1 = p1.next; p2 = p2.next; } return null; } private int getLength(ListNode head) { ListNode p = head; int count = 0; while (p != null) { count++; p = p.next; } return count; }}
0 0
- 剑指Offer_36_两个链表的第一个公共结点
- 两个链表的第一个公共结点(剑指offer37)
- 【剑指offer】两个链表的第一个公共结点
- 剑指offer--两个链表的第一个公共结点
- 《剑指offer》两个链表的第一个公共结点
- 剑指offer 两个链表的第一个公共结点
- 剑指offer:两个链表的第一个公共结点
- [剑指offer]两个链表的第一个公共结点
- 剑指offer---两个链表的第一个公共结点
- 剑指offer|两个链表的第一个公共结点
- 剑指offer-两个链表的第一个公共结点
- 《剑指offer》-两个链表的第一个公共结点
- 剑指Offer: 两个链表的第一个公共结点
- 剑指offer_两个链表的第一个公共结点
- 剑指offer:两个链表的第一个公共结点
- 剑指offer 两个链表的第一个公共结点
- 剑指offer--两个链表的第一个公共结点
- 剑指offer:两个链表的第一个公共结点
- C++中的运行时类型检查
- 触发器 写入数据
- 空气质量
- struct timeval结构体
- 用iReport设置pdf模版
- 剑指Offer_36_两个链表的第一个公共结点
- 单例模式 来自百度百科
- nodejs实现,每天定时自动读取数据库数据-生成excel表格-发送给老板邮箱(promise版)
- Pix4D 入门手册
- 在ubuntu上使用swarm搭建docker集群
- hdu 1047 1042 java 大整数
- 驰骋工作流引擎衍生产品CCOA 迁移到git开源平台 公告
- WPF中的事件(三)- 附加事件
- 第2章 C#编程概述