|
6 | 6 |
|
7 | 7 | # 143.重排链表
|
8 | 8 |
|
| 9 | +[力扣题目链接](https://leetcode.cn/problems/reorder-list/submissions/) |
| 10 | + |
9 | 11 | 
|
10 | 12 |
|
11 | 13 | ## 思路
|
@@ -465,7 +467,81 @@ var reorderList = function(head, s = [], tmp) {
|
465 | 467 | }
|
466 | 468 | ```
|
467 | 469 |
|
| 470 | +### TypeScript |
| 471 | + |
| 472 | +> 辅助数组法: |
| 473 | + |
| 474 | +```typescript |
| 475 | +function reorderList(head: ListNode | null): void { |
| 476 | + if (head === null) return; |
| 477 | + const helperArr: ListNode[] = []; |
| 478 | + let curNode: ListNode | null = head; |
| 479 | + while (curNode !== null) { |
| 480 | + helperArr.push(curNode); |
| 481 | + curNode = curNode.next; |
| 482 | + } |
| 483 | + let node: ListNode = head; |
| 484 | + let left: number = 1, |
| 485 | + right: number = helperArr.length - 1; |
| 486 | + let count: number = 0; |
| 487 | + while (left <= right) { |
| 488 | + if (count % 2 === 0) { |
| 489 | + node.next = helperArr[right--]; |
| 490 | + } else { |
| 491 | + node.next = helperArr[left++]; |
| 492 | + } |
| 493 | + count++; |
| 494 | + node = node.next; |
| 495 | + } |
| 496 | + node.next = null; |
| 497 | +}; |
| 498 | +``` |
| 499 | + |
| 500 | +> 分割链表法: |
| 501 | + |
| 502 | +```typescript |
| 503 | +function reorderList(head: ListNode | null): void { |
| 504 | + if (head === null || head.next === null) return; |
| 505 | + let fastNode: ListNode = head, |
| 506 | + slowNode: ListNode = head; |
| 507 | + while (fastNode.next !== null && fastNode.next.next !== null) { |
| 508 | + slowNode = slowNode.next!; |
| 509 | + fastNode = fastNode.next.next; |
| 510 | + } |
| 511 | + let head1: ListNode | null = head; |
| 512 | + // 反转后半部分链表 |
| 513 | + let head2: ListNode | null = reverseList(slowNode.next); |
| 514 | + // 分割链表 |
| 515 | + slowNode.next = null; |
| 516 | + /** |
| 517 | + 直接在head1链表上进行插入 |
| 518 | + head1 链表长度一定大于或等于head2, |
| 519 | + 因此在下面的循环中,只要head2不为null, head1 一定不为null |
| 520 | + */ |
| 521 | + while (head2 !== null) { |
| 522 | + const tempNode1: ListNode | null = head1!.next, |
| 523 | + tempNode2: ListNode | null = head2.next; |
| 524 | + head1!.next = head2; |
| 525 | + head2.next = tempNode1; |
| 526 | + head1 = tempNode1; |
| 527 | + head2 = tempNode2; |
| 528 | + } |
| 529 | +}; |
| 530 | +function reverseList(head: ListNode | null): ListNode | null { |
| 531 | + let curNode: ListNode | null = head, |
| 532 | + preNode: ListNode | null = null; |
| 533 | + while (curNode !== null) { |
| 534 | + const tempNode: ListNode | null = curNode.next; |
| 535 | + curNode.next = preNode; |
| 536 | + preNode = curNode; |
| 537 | + curNode = tempNode; |
| 538 | + } |
| 539 | + return preNode; |
| 540 | +} |
| 541 | +``` |
| 542 | +
|
468 | 543 | ### C
|
| 544 | +
|
469 | 545 | 方法三:反转链表
|
470 | 546 | ```c
|
471 | 547 | //翻转链表
|
|
0 commit comments