您的位置:首页 > 其它

Easy-题目38:160. Intersection of Two Linked Lists

2016-05-30 20:28 260 查看
题目原文:

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.

题目大意:

求两个单链表的交点。

题目分析:

考研数据结构复习的时候见过此题,应该是链表处理的题目中比较经典的一道。解法是求出两个链表的长度,然后两个指针分别指向两个链表的头结点,先让较长的链表的指针走过差值的步数,这样两个指针距离尾节点的距离就相同了,让两个节点并行走直到遇到交点。

源码:(language:c)

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
if(!headA||!headB)
return NULL;
struct ListNode *p;
int lengtha,lengthb;
for(p=headA,lengtha=0;p;p=p->next,lengtha++);
for(p=headB,lengthb=0;p;p=p->next,lengthb++);

if(lengtha>lengthb) {
for(int i=0;i<lengtha-lengthb;i++)
headA=headA->next;
}
else if (lengthb>lengtha) {
for(int i=0;i<lengthb-lengtha;i++)
headB=headB->next;
}
while(headA!=headB) {
headA=headA->next;
headB=headB->next;
}
return headA;
}


成绩:

32ms,beats 18.75%,众数32ms,78.91%

cmershen的碎碎念:

这道题比较经典,但如果不给出这个算法,自己是很难想到的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: