《剑指offer》——两个链表的第一个公共结点
来源:互联网 发布:行业大盘数据分析 编辑:程序博客网 时间:2024/06/01 23:27
时间复杂度为O(m+n)。
struct ListNode{ int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL){}};ListNode* FindFirstCommonNode( ListNode *pHead1, ListNode *pHead2) { ListNode* pFirstCommonNode = NULL; if(pHead1 == NULL || pHead2 == NULL)//若输入链表有一个为空,返回空结点 return pFirstCommonNode; ListNode* pNode1 = pHead1; ListNode* pNode2 = pHead2; int pLen1 = 0, pLen2 = 0; while(pNode1)//分别计算两个链表的长度 { pNode1 = pNode1 -> next; pLen1++; } while(pNode2) { pNode2 = pNode2 -> next; pLen2++; } int offSet = 0; if(pLen1 < pLen2)//移动链表的头结点,将长链表的头结点与短链表的头结点对齐 { offSet = pLen2 - pLen1; while(offSet) { pHead2 = pHead2 -> next; offSet--; } } else if(pLen2 < pLen1) { offSet = pLen1 - pLen2; while(offSet) { pHead1 = pHead1 -> next; offSet--; } } while(pHead1 && pHead2)//如果当前结点不相等,则继续同步遍历两个链表直到找到第一个公共结点 { if(pHead1 == pHead2) { pFirstCommonNode = pHead1; break; } else { pHead1 = pHead1 -> next; pHead2 = pHead2 -> next; } } return pFirstCommonNode;//返回第一个公共结点}
0 0
- 【剑指offer】两个链表的第一个公共结点
- 剑指offer--两个链表的第一个公共结点
- 《剑指offer》两个链表的第一个公共结点
- 剑指offer 两个链表的第一个公共结点
- 剑指offer:两个链表的第一个公共结点
- [剑指offer]两个链表的第一个公共结点
- 剑指offer---两个链表的第一个公共结点
- 剑指offer|两个链表的第一个公共结点
- 剑指offer-两个链表的第一个公共结点
- 《剑指offer》-两个链表的第一个公共结点
- 剑指Offer: 两个链表的第一个公共结点
- 剑指offer:两个链表的第一个公共结点
- 剑指offer 两个链表的第一个公共结点
- 剑指offer--两个链表的第一个公共结点
- 剑指offer:两个链表的第一个公共结点
- 剑指Offer------两个链表的第一个公共结点
- 剑指offer--两个链表的第一个公共结点
- 剑指offer---两个链表的第一个公共结点
- jquery.cookie.js用法实例详解
- tomcat中catalina是什么
- 19Java语法回顾之反射
- Redis 横向扩展案例
- Hadoop YARN学习监控JVM和实时监控Ganglia、Ambari(5)
- 《剑指offer》——两个链表的第一个公共结点
- unity 中抗锯齿设置
- Leetcode 326. Power of Three
- 如何利用fsolve求方程组[matlab]
- 介绍两个分布式数据库开源系统
- JAVA Exception 处理
- 程序员,一个吃青春饭的行业
- android-gpuimage-master 编译失败
- Struts2-表单验证的两种方式