題目:
Write a program to find the node at which the intersection of two singly linked lists begins.
Notice
If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
思路:
- 先找出哪一條比較常,然後把 head長移動位置,讓兩條 linked list 出發點相同
代碼:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/*
* @param headA: the first list
* @param headB: the second list
* @return: a ListNode
*/
ListNode * getIntersectionNode(ListNode * headA, ListNode * headB) {
// write your code here
if (headA == NULL || headB == NULL)
return NULL;
int lenA = 0;
int lenB = 0;
ListNode* nodeA = headA;
ListNode* nodeB = headB;
while(nodeA!=NULL){
lenA++;
nodeA = nodeA->next;
}
while(nodeB!=NULL){
lenB++;
nodeB = nodeB->next;
}
int N = abs(lenB-lenA);
if(lenB > lenA) {
for(int i = 0; i < N; i++){
headB = headB->next;
}
}
else if(lenA > lenB){
for(int i = 0; i < N; i++){
headA = headA->next;
}
}
while(headA != headB){
headA = headA->next;
headB = headB->next;
}
return headA;
}
};
网友评论