Intersection of Two Linked Lists--leetcode
来源:互联网 发布:高速公路收费计算软件 编辑:程序博客网 时间:2024/05/21 10:14
原题链接:https://oj.leetcode.com/problems/intersection-of-two-linked-lists/
题目大意:给定两个单链表,若相交则找出第一个交点。
解题思路:如果两个无环单链表相交,则必定尾部结点为同一个结点。设定两个指针,若从两个链表的表头同时遍历,很明显不能找到交点。但若将较长的链表截去长出来的一部分,然后两个指针同时遍历,则第一次两个指针相等的结点明显是所求结点。若走到链表尾,任然未相交,则两个链表未相交。
class Solution {public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if(headA==NULL||headB==NULL) return NULL; ListNode *p1,*p2; p1=headA,p2=headB; int lenA=0,lenB=0; while(p1){ lenA++; p1=p1->next; } while(p2){ lenB++; p2=p2->next; } p1=headA,p2=headB; while(lenA<lenB){ p2=p2->next; lenA++; } while(lenB<lenA){ p1=p1->next; lenB++; } while(p1&&p2){ if(p1==p2) return p1; p1=p1->next; p2=p2->next; } return NULL; }};
因为没有环,所以题目比较简单。题目比较经典,可以扩展到有环的情况下,大家可以考虑下哈。
1 0
- [leetcode] [leetcode]Intersection of Two Linked Lists
- 【LeetCode】Intersection of Two Linked Lists
- LeetCode: Intersection of Two Linked Lists
- [Leetcode] Intersection of Two Linked Lists
- [Leetcode]Intersection of Two Linked Lists
- LeetCode:Intersection of Two Linked Lists
- leetcode: Intersection of Two Linked Lists
- Leetcode: Intersection of Two Linked Lists
- Intersection of Two Linked Lists--leetcode
- [leetcode]Intersection of Two Linked Lists
- leetcode:Intersection of Two Linked Lists
- leetcode之Intersection of Two Linked Lists
- 【Leetcode】:Intersection of Two Linked Lists
- leetcode Intersection of Two Linked Lists
- [LeetCode]Intersection of Two Linked Lists
- leetcode: Intersection of Two Linked Lists
- 【LeetCode】Intersection of Two Linked Lists
- LeetCode Intersection of Two Linked Lists
- 北斗导航系统关键设备全面进入消费电子领域
- C#编程学习笔记
- 黑马程序员-objective-c学习总结
- eclipse生成jar包和用别人jar包的方法
- PHP 重写读取文件,适用多域名的情况!
- Intersection of Two Linked Lists--leetcode
- 【Qt开发-模拟电商网站】模态与非模态窗口
- request.getQueryString()的意思
- 策略模式
- AlertDialog与Dialog的区别以及一个奇怪的问题1
- windows8.1 explorer.exe win+E 出现“该文件没有与之关联的程序…………”解决办法
- makefile详解 函数 foreach if call origin shell
- 7. Dubbo原理解析-与spring融合
- 20141201股票账户总结