總是想要先寫出來再說......
好像不是一個好習慣 ?!
給兩個linked list
找出它們從哪裡開始重疊
(或者說從哪裡開始是一樣的)
我好笨解法:
Intersection of Two Linked Lists
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
if (headA == NULL || headB == NULL)
return NULL;
if (headA == headB)
return headA;
struct ListNode *t1, *t2;
for(t1=headA;t1->next != NULL; t1 =t1->next)
{
for(t2=headB;t2->next != NULL; t2 =t2->next)
{
if (t1 == t2)
return t1;
}
}
for(t2=headB;t2->next != NULL; t2 =t2->next)
{
if (t1 == t2)
return t2;
}
if (t1 == t2)
return t2;
return NULL;
}
然後就是看了別人解法果然還是我真的好笨.......
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
if (headA == NULL || headB == NULL)
return NULL;
if (headA == headB)
return headA;
struct ListNode *t1, *t2;
int i=0,l1=1,l2=1;
for(t1=headA;t1->next != NULL; t1 =t1->next)
l1++;
for(t2=headB;t2->next != NULL; t2 =t2->next)
l2++;
t1 = headA;
t2 = headB;
if (l1 > l2)
for(i=0;i++<(l1-l2); t1 =t1->next)
;
else if (l1 < l2)
for(i=0;i++<(l2-l1); t2 =t2->next)
;
while(t1 != NULL && t2 != NULL)
{
if (t1 == t2)
return t1;
t1 = t1->next;
t2 = t2->next;
}
return NULL;
}
沒有留言:
張貼留言