[LintCode]380.两个链表的交叉
来源:互联网 发布:模板引擎 node 编辑:程序博客网 时间:2024/05/18 01:13
请写一个程序,找到两个单链表最开始的交叉节点。
注意事项
- 如果两个链表没有交叉,返回
null
。 - 在返回结果后,两个链表仍须保持原有的结构。
- 可假定整个链表结构中没有循环。
下列两个链表:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
在节点 c1 开始交叉。
2.链表2从头节点开始,走到最后一个节点(不是结束),统计链表2的长度记为len2,,同时一记录链表2的最后一个节点记为curB
3.如果curA!=curB,说明两个链表不相交,返回NULL即可;如果curA==curB,说明两个链表相交,进入步骤4来找寻第一个相交节点。
4.如果链表1比较长,链表1就先走len1-len2步;如果链表2比较长,链表2就先走len2-len1步。然后两个链表一起走,一起走的过程中,两个链表第一次走到一起的那个节点,就是第一个相交的节点。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: /** * @param headA: the first list * @param headB: the second list * @return: a ListNode */ ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if(headA==NULL||headB==NULL){ return NULL; } ListNode *curA=headA; ListNode *curB=headB; int len1=0,len2=0; while(curA->next!=NULL){ //链表1从头节点开始,走到最后一个节点 len1++; //链表1的长度 curA=curA->next; } while(curB->next!=NULL){ //链表2从头节点开始,走到最后一个节点 len2++; //链表2的长度 curB=curB->next; } if(curA!=curB){ //遍历到最后,如果curA!=curB,说明两个链表不相交 return NULL; } //这里需要初始化 curA=headA; curB=headB; int res=len1-len2; if(res>0) //链表1比较长,链表1就先走len1-len2步 for(int i=0;i<res;i++){ curA=curA->next; } if(res<0) //如果链表2比较长,链表2就先走len2-len1步 for(int i=0;i<abs(res);i++){ curB=curB->next; } while(curA!=curB){ //开始齐头并进,直到找到第一个公共结点 curA=curA->next; curB=curB->next; } return curA; }};
阅读全文
1 0
- [LintCode]380.两个链表的交叉
- Lintcode 两个链表的交叉
- LintCode: 两个链表的交叉
- lintcode ----两个链表的交叉
- lintcode-两个链表的交叉
- LintCode:M-两个链表的交叉
- 两个链表的交叉-LintCode
- LintCode-剑指Offer-(380)两个链表的交叉
- lintcode刷题——两个链表的交叉
- [Lintcode]Intersection of Two Linked Lists 两个链表的交叉
- lintcode 交叉链表
- 两个链表的交叉
- 两个链表的交叉
- 两个链表的交叉
- LintCode 两个链表的和
- LintCode-两个链表的和
- Lintcode 合并两个排序的链表
- LintCode-两个链表的和sum
- zcmu---1670: 和费马开个玩笑
- 滑雪(dp+搜索)
- 深度学习系列教程
- darken函数是怎么计算的呢?
- 成为一名Java高级工程师你需要学什么
- [LintCode]380.两个链表的交叉
- Jsp学习
- 关注民生民情
- 剑指offer_机器人的运动范围
- Linux shell 命令行最实用的快捷键
- 51nod--1770数数字
- Solidworks与Matlab联合仿真&SimMechnics下载及安装
- ~智能指针~
- ubuntu编译工程出现: fatal error: error writing to /tmp/cc1ezU8m.s: No space left on device