File tree Expand file tree Collapse file tree 2 files changed +58
-10
lines changed
0160_intersection_of_two_linked_list Expand file tree Collapse file tree 2 files changed +58
-10
lines changed Original file line number Diff line number Diff line change @@ -9,23 +9,27 @@ struct ListNode {
9
9
10
10
static struct ListNode * getIntersectionNode (struct ListNode * headA , struct ListNode * headB )
11
11
{
12
+ if (headA == NULL || headB == NULL ) {
13
+ return NULL ;
14
+ }
15
+
12
16
struct ListNode * p ;
13
17
for (p = headA ; p -> next != NULL ; p = p -> next ) {}
14
18
p -> next = headB ;
15
19
16
- bool first = true;
17
- struct ListNode * p0 , * p1 ;
18
- for (p0 = headA , p1 = headA ; p1 != NULL && p1 -> next != NULL ; p0 = p0 -> next , p1 = p1 -> next -> next ) {
19
- if (p0 == p1 && !first ) {
20
- p0 = headA ;
21
- while (p0 != p1 ) {
22
- p0 = p0 -> next ;
23
- p1 = p1 -> next ;
20
+ struct ListNode * slow = headA , * fast = headA ;
21
+ while (fast != NULL && fast -> next != NULL ) {
22
+ slow = slow -> next ;
23
+ fast = fast -> next -> next ;
24
+ if (slow == fast ) {
25
+ slow = headA ;
26
+ while (slow != fast ) {
27
+ slow = slow -> next ;
28
+ fast = fast -> next ;
24
29
}
25
30
p -> next = NULL ;
26
- return p0 ;
31
+ return slow ;
27
32
}
28
- first = false;
29
33
}
30
34
31
35
p -> next = NULL ;
Original file line number Diff line number Diff line change
1
+ #include < stdc++.h>
2
+
3
+ using namespace std ;
4
+
5
+ /* *
6
+ * Definition for singly-linked list.
7
+ * struct ListNode {
8
+ * int val;
9
+ * ListNode *next;
10
+ * ListNode(int x) : val(x), next(NULL) {}
11
+ * };
12
+ */
13
+ class Solution {
14
+ public:
15
+ ListNode *getIntersectionNode (ListNode *headA, ListNode *headB) {
16
+ int lenA = getListLength (headA);
17
+ int lenB = getListLength (headB);
18
+ if (lenA > lenB) {
19
+ for (int i = 0 ; i < lenA - lenB; i++) {
20
+ headA = headA->next ;
21
+ }
22
+ } else {
23
+ for (int i = 0 ; i < lenB - lenA; i++) {
24
+ headB = headB->next ;
25
+ }
26
+ }
27
+
28
+ while (headA != nullptr && headB != nullptr && headA != headB) {
29
+ headA = headA->next ;
30
+ headB = headB->next ;
31
+ }
32
+
33
+ return headA;
34
+ }
35
+ private:
36
+ int getListLength (ListNode *h) {
37
+ int len = 0 ;
38
+ while (h != nullptr ) {
39
+ len++;
40
+ h = h->next ;
41
+ }
42
+ return len;
43
+ }
44
+ };
You can’t perform that action at this time.
0 commit comments