[LeedCode OJ]#160 Intersection of Two Linked Lists
来源:互联网 发布:导弹惯性制导难度知乎 编辑:程序博客网 时间:2024/06/05 01:06
【 声明:版权所有,转载请标明出处,请勿用于商业用途。 联系信箱:libin493073668@sina.com】
题目链接:https://leetcode.com/problems/intersection-of-two-linked-lists/
题意:
给定两个链表,要求找出这两个链表的交点
思路:
我们可以设定两个指针,分别遍历得到a,b的长度,然后如果a长,就将a的指针从头指针往下移动k位直到与b指针等长的位置,b链表长也是如此。
然后两个指针同时出发,一旦走到相同的位置,那么这个位置就是两个链表的交点
/** * 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){int la = 0,lb = 0;ListNode *pa = headA;ListNode *pb = headB;while(pa){la++;pa = pa->next;}while(pb){lb++;pb = pb->next;}pa = headA;pb = headB;if(la<lb){int cnt = lb - la;while(cnt--){pb = pb->next;}}else if(la>lb){int cnt = la - lb;while(cnt--){pa = pa->next;}}while(pa!=pb){pa = pa->next;pb = pb->next;}return pa;}};
0 0
- [LeedCode OJ]#160 Intersection of Two Linked Lists
- LeetCode OJ Intersection of Two Linked Lists
- leetcode 160-Intersection of Two Linked Lists
- 160 Intersection of Two Linked Lists
- leetcode 160: Intersection of Two Linked Lists
- LeetCode(160) Intersection of Two Linked Lists
- [leetcode 160] Intersection of Two Linked Lists
- leetCode #160 Intersection of Two Linked Lists
- LeetCode(160) Intersection of Two Linked Lists
- LeetCode[160]Intersection of Two Linked Lists
- 160Intersection of Two Linked Lists
- [LeetCode 160]Intersection of Two Linked Lists
- [LeetCode][160][Intersection of Two Linked Lists ]
- leetcode-160 Intersection of Two Linked Lists
- leetcode 160Intersection of Two Linked Lists
- LeetCode 160 :Intersection of Two Linked Lists
- 160Intersection of Two Linked Lists
- #160 Intersection of Two Linked Lists
- 宣告主权
- COCI CONTEST #3 29.11.2014 HONI
- 查看端口被占用
- 虚幻引擎3命令行参数
- iOS 字符串中去除特殊符号 stringByTrimmingCharactersInSet
- [LeedCode OJ]#160 Intersection of Two Linked Lists
- 启用mysqli扩展模块
- IP地址的分类——a,b,c 类是如何划分的
- 97 AFNetworking文件上传
- myeclipse安装svn插件的多种方式
- 在同一台机器上运行多个 MySQL 服务
- 第2周项目0宣告“主权”
- 程序员的数学2:概率统计——互动出版网
- 1.1 MFC对话框背景设置