leetcode之判断两链表首次交汇节点
来源:互联网 发布:谷歌seo公司 编辑:程序博客网 时间:2024/05/14 04:47
题目:
Intersection of Two Linked Lists
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
- If the two linked lists have no intersection at all, return
null
. - The linked lists must retain their original structure after the function returns.
- You may assume there are no cycles anywhere in the entire linked structure.
- Your code should preferably run in O(n) time and use only O(1) memory.
思路:先遍历左链表,再遍历右链表,遍历的时候分别计数,遍历完成后,如果最后一个节点不同,则没有交点,否则,可判断有交点,在有交点的情况下,看两条链表的便利次数M,N,然后再重新遍历,不过这次遍历先让长的那条链表先走|M-N|步,然后两边同时向前,每一步判断节点地址是否相等,第一次相等的即为首个交汇点。逻辑就是这样,但是这里有一些边界条件必须注意,否则,有了这个思路一样会出错。
代码
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode* p1=headA; ListNode* p2=headB; if(p1==NULL||p2==NULL) { return NULL; } if(p1==p2) { return p1; } int i=1; int j=1; while(p1->next!=NULL) { p1=p1->next; i++; } while(p2->next!=NULL) { p2=p2->next; j++; } //no intersection, last node not the same if(p1!=p2) { return NULL; } //else p1=headA; p2=headB; if(i>j) { int diff=i-j; while(diff>0) { p1=p1->next; diff--; } }else if(j>i) { int diff=j-i; while(diff>0) { p2=p2->next; diff--; } } if(p1==p2) { return p1; } while(p1->next!=p2->next) { p1=p1->next; p2=p2->next; } return p1->next; }};
0 0
- leetcode之判断两链表首次交汇节点
- 如何判断一个单链表有环,并且求出交汇处
- 判断程序首次启动
- iOS 判断首次启动
- iOS-判断首次启动
- leetcode之返回交叉的节点
- 判断App是否首次启动
- Android判断是否首次登录
- iosApp首次次运行判断
- JS判断页面首次访问
- [LeetCode] 判断两个链表是否有公共节点并返回第一个公共节点
- [LeetCode] 判断两个链表是否有公共节点并返回第一个公共节点
- iOS之引导页开发(一)——采用NSUserDefaults进行首次运行判断
- 关于 如何判断-浏览器首次访问判断
- jbpm系列之五--使用decision节点判断分支情况
- Leetcode 160 寻找两链表的交叉节点
- LeetCode之判断高度平衡二叉树
- leetcode之判断中心对称二叉树
- 从Linux内核镜像中提取内核配置文件
- centos中文输入法设定
- IT工具介绍
- 6.struts国际化
- 操作系統常見知識複習(一)
- leetcode之判断两链表首次交汇节点
- Unity3D之实现增,减,删,改方法
- Android -- 播放视频的两种形式
- 操作系統常見知識複習(二)
- highcharts之column3D
- HDU 2608 0 or 1(数论)
- 常见的操作系统使用的文件系统整理
- 基于虚拟机的centos版本linux操作系统如何联网
- Eclipse快捷键