好像不是一個好習慣 ?!給兩個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;
}
(怎麼沒辦法插入繼續閱讀 XD)
[20251110] 更新
原來當年之後已經有好精簡寫法了Orz 偷看了答案再寫,寫出了無窮迴圈XD
要注意原本的headA跟headB在後面還會用到,所以不能讓它自己跑去 next,
要另外用pointer來寫~以上。
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode *p1 = headA;
struct ListNode *p2 = headB;
while (p1 != p2)
{
if (p1==NULL)
p1 = headB;
else
p1 = p1->next;
if (p2==NULL)
p2 = headA;
else
p2 = p2->next;
}
return p1;
}
沒有留言:
張貼留言