【leetcode】Intersection of Two Linked Lists
2015-05-07 18:42
218 查看
Intersection of Two Linked Lists
Write a program to find the node at which the intersection of two singly linked lists begins.For example, the following two linked lists:
begin to intersect at node c1.
思路:
链表的题目第一次一次通过。。。基本思路就两个链表的长度差就是两个链表在相交之前数据的个数差,找到这个差之后,再一对一逐个对比,就可以了。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if(headA==NULL||headB==NULL) return NULL; ListNode *res, *p1, *p2; p1=headA; p2=headB; int a=0,b=0; while(p1&&p2) { p1=p1->next; p2=p2->next; a++;b++; } while(p1){p1=p1->next;a++;} while(p2){p2=p2->next;b++;} int delta=abs(a-b); p1=headA; p2=headB; if(a>=b) { for(int i=0;i<delta;i++) { p1=p1->next; } } else { for(int i=0;i<delta;i++) { p2=p2->next; } } while(p1&&p2) { if(p1->val==p2->val) return p1; else { p1=p1->next; p2=p2->next; } } return NULL; } };
相关文章推荐
- Leetcode-Intersection of Two Linked Lists
- 【leetcode】Intersection of Two Linked Lists
- LeetCode 160 :Intersection of Two Linked Lists
- 【Leetcode】Intersection of Two Linked Lists
- 刷leetcode:Intersection of Two Linked Lists
- Intersection of Two Linked Lists--leetcode
- [LeetCode]Intersection of Two Linked Lists
- [leetcode]#160 Intersection of Two Linked Lists
- 【LeetCode 160】Intersection of Two Linked Lists
- Leetcode45:Intersection of Two Linked Lists
- LeetCode 160 Intersection of Two Linked Lists
- 【LeetCode】160 - Intersection of Two Linked Lists
- LeetCode Intersection of Two Linked Lists
- leetcode 160 Intersection of Two Linked Lists
- leetcode[160] Intersection of Two Linked Lists
- leetcode---Intersection of Two Linked Lists
- leetcode Intersection of Two Linked Lists
- [LeetCode] Intersection of Two Linked Lists
- Leetcode: Intersection of Two Linked Lists
- LeetCode_Intersection of Two Linked Lists