题目链接:https://oj.leetcode.com/problems/intersection-of-two-linked-lists/
Runtimes:81ms
1、问题
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.
2、分析
有个特例,如果两条链表长度刚好相等,那么两个指针齐头并进就能够找到第一个相等的指针。但是现实当中两条链表的长度不一定相等,那么就应该将不等转换成为相等,就同样可以解决问题。
3、小结
对于不等的算例,首先获得两条链表A、B的长度La和Lb,假如La < Lb,那么从A的头和B的(Lb - La)位置开始同时遍历,直到两个位置的指针相等。
4、实现
/**
* 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 *p = headA;
ListNode *q = headB;
int la = 0, lb = 0;
while(p)
{
la++;
p = p->next;
}
while(q)
{
lb++;
q = q->next;
}
p = headA; q = headB;
if(la > lb)
{
while(la-- > lb)
p = p->next;
}else if(la < lb)
{
while(lb-- > la)
q = q->next;
}
while(p != q)
{
p = p->next;
q = q->next;
}
return p;
}
};
5、反思
感觉自己脑袋容易被已有的信息局限住,比如一直纠结着O(n)的时间复杂度,上面解法的时间复杂度也是O(n+m),两条链表要同时遍历一次才行。其次编程过程中把判断条件p 写成了!p,囧。
听说有另外一种解法,看看。
文章链接:http://www.cnblogs.com/yuzhangcmu/p/4128794.html