Skip to content

Commit 1e68f64

Browse files
Merge pull request youngyangyang04#1010 from xiaofei-2020/ts6
添加(面试题02.07.链表相交.md):增加typescript版本
2 parents 0b8bd71 + ba8e46f commit 1e68f64

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

problems/面试题02.07.链表相交.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,43 @@ var getIntersectionNode = function(headA, headB) {
239239
};
240240
```
241241

242+
TypeScript:
243+
244+
```typescript
245+
function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null {
246+
let sizeA: number = 0,
247+
sizeB: number = 0;
248+
let curA: ListNode | null = headA,
249+
curB: ListNode | null = headB;
250+
while (curA) {
251+
sizeA++;
252+
curA = curA.next;
253+
}
254+
while (curB) {
255+
sizeB++;
256+
curB = curB.next;
257+
}
258+
curA = headA;
259+
curB = headB;
260+
if (sizeA < sizeB) {
261+
[sizeA, sizeB] = [sizeB, sizeA];
262+
[curA, curB] = [curB, curA];
263+
}
264+
let gap = sizeA - sizeB;
265+
while (gap-- && curA) {
266+
curA = curA.next;
267+
}
268+
while (curA && curB) {
269+
if (curA === curB) {
270+
return curA;
271+
}
272+
curA = curA.next;
273+
curB = curB.next;
274+
}
275+
return null;
276+
};
277+
```
278+
242279
C:
243280

244281
```c

0 commit comments

Comments
 (0)