-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
fb555eb
commit 17ccfaf
Showing
1 changed file
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
#include "common.h" | ||
|
||
using namespace std; | ||
|
||
namespace s0160 { | ||
// Definition for singly-linked list. | ||
struct ListNode { | ||
int val; | ||
ListNode *next; | ||
ListNode() : val(0), next(nullptr) {} | ||
ListNode(int x) : val(x), next(nullptr) {} | ||
ListNode(int x, ListNode *next) : val(x), next(next) {} | ||
}; | ||
class Solution { | ||
public: | ||
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { | ||
int lenA = 0, lenB = 0; | ||
ListNode* t1 = headA, *t2 = headB; | ||
while (t1) { | ||
lenA++; | ||
t1 = t1->next; | ||
} | ||
while (t2) { | ||
lenB++; | ||
t2 = t2->next; | ||
} | ||
t1 = headA; | ||
t2 = headB; | ||
if (lenB > lenA) { | ||
swap(lenA, lenB); | ||
swap(t1, t2); | ||
} | ||
int val = lenA - lenB; | ||
while(val--) { | ||
t1 = t1->next; | ||
} | ||
|
||
while (t1) { | ||
if (t1 == t2) { | ||
return t1; | ||
} | ||
t1 = t1->next; | ||
t2 = t2->next; | ||
} | ||
return nullptr; | ||
} | ||
}; | ||
} |