题目链接:https://oj.leetcode.com/problems/intersection-of-two-linked-lists/
分析:题目就是求两个链表的的第一个交点,如果没有交点,那么返回NULL。所谓两个链表有交点,那么两个链表的形状一定是"Y"的形状,不可能是"X"形状。
算法一:暴力遍历(时间复杂度O(m*n),空间复杂度O(1))
对于链表A中的每一个节点ai,遍历整个链表B检测节点ai是否在B中。
算法二:哈希表(O(m+n)时间复杂度,空间复杂度O(n)或者O(m))
遍历链表A然后将A中的每个节点ai的地址放在hash表中,然后遍历链表B中的每一个节点bi,如果bi出现在hash表中,那么bi一定是交点。
算法三:两个指针(O(m+n)时间复杂度,空间复杂度O(1))
首先计算两个链表的长度,记为la、lb,然后让较长的那个链表的表头指针走abs(la-lb)次,那么两个表的表头指针距离链表尾部长度一定一样,然后两个链表一起走,即可判断。
AC代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int getListLen(ListNode *head)
{
if(head == NULL)
{
return 0;
}
int cnt = 0;
while(head!=NULL)
{
cnt++;
head = head->next;
}
return cnt;
}
ListNode * getIntersectionNode(ListNode *headA,ListNode *headB)
{
if( headA == NULL || headB == NULL ) return NULL;
int la = 0,lb = 0;
la = getListLen(headA);
lb = getListLen(headB);
int dis = la > lb ? la - lb : lb - la;
if(la>lb)
{
while(dis--)
{
headA = headA -> next;
}
}
else
{
while(dis--)
{
headB = headB -> next;
}
}
while(headA!=headB)
{
headA = headA->next;headB = headB->next;
}
return headA;
}
};#include<iostream>
#include<cmath>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x),next(NULL) {}
};
class Solution
{
public:
Solution(ListNode *&ha,ListNode *&hb,int a[],int la,int b[],int lb)
{
ha = new ListNode(a[0]);
ListNode *p = ha;
ListNode *inter;
for(int i=1;i<la;i++)
{
ListNode *tmp = new ListNode(a[i]);
if(i==3) inter = p;
p->next = tmp;
p=p->next;
}
hb = new ListNode(b[0]);
p = hb;
for(int i=1;i<lb;i++)
{
ListNode *tmp = new ListNode(b[i]);
p->next = tmp;
p = p->next;
}
ListNode *tail = p;
tail->next = inter;
}
void print(ListNode *ha,ListNode *hb)
{
cout<<"a:";
while(ha!=NULL)
{
cout<<ha->val<<" ";
ha = ha->next;
}
cout<<endl;
cout<<"b:";
while(hb!=NULL)
{
cout<<hb->val<<" ";
hb = hb->next;
}
cout<<endl;
}
int getListLen(ListNode *head)
{
if(head == NULL)
{
return 0;
}
int cnt = 0;
while(head!=NULL)
{
cnt++;
head = head->next;
}
return cnt;
}
ListNode * getIntersectionNode(ListNode *headA,ListNode *headB)
{
if( headA == NULL || headB == NULL ) return NULL;
int la = 0,lb = 0;
la = getListLen(headA);
lb = getListLen(headB);
int dis = la > lb ? la - lb : lb - la;
if(la>lb)
{
while(dis--)
{
headA = headA -> next;
}
}
else
{
while(dis--)
{
headB = headB -> next;
}
}
while(headA!=headB)
{
headA = headA->next;headB = headB->next;
}
return headA;
}
};
int main()
{
int a[] = {1,3,5,6,7,8};
int b[] = {0,2,4};
ListNode *ha,*hb;
Solution s( ha,hb,a,sizeof(a)/sizeof(a[0]),b,sizeof(b)/sizeof(b[0]) );
s.print(ha,hb);
ListNode *res = s.getIntersectionNode(ha,hb);
cout<<res->val<<endl;
return 0;
}
Leetcode:Intersection of Two Linked Lists
原文地址:http://blog.csdn.net/lavorange/article/details/41701831