Skip to content

Commit

Permalink
add 160
Browse files Browse the repository at this point in the history
  • Loading branch information
caixiangyue committed Aug 28, 2023
1 parent fb555eb commit 17ccfaf
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions 0160.h
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;
}
};
}

0 comments on commit 17ccfaf

Please sign in to comment.