标签:style win nbsp 写法 example 简单的 any 最坏情况 sum
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.
Notes:
null
.1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * struct ListNode *next; 6 * }; 7 */ 8 struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) { 9 if(!headA || !headB) return NULL; 10 struct ListNode *pa=headA,*pb=headB; 11 while(1){ 12 if(pa==pb) 13 return pa; 14 else if(!pa->next && !pb->next) 15 return NULL; 16 else{ 17 if(pa->next) 18 pa=pa->next; 19 else 20 pa=headB; 21 if(pb->next) 22 pb=pb->next; 23 else 24 pb=headA; 25 } 26 } 27 }
看到别的大神更简洁的写法,同样的原理:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * struct ListNode *next; 6 * }; 7 */ 8 struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) { 9 if(!headA || !headB) return NULL; 10 struct ListNode *pa=headA,*pb=headB; 11 while(pa!=pb){ 12 pa=pa==NULL?headB:pa->next; 13 pb=pb==NULL?headA:pb->next; 14 } 15 return pa; 16 }
160. Intersection of Two Linked Lists
标签:style win nbsp 写法 example 简单的 any 最坏情况 sum
原文地址:https://www.cnblogs.com/real1587/p/9886734.html