# 题目
给定一个头结点为 head
的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
# 自己解题
完全按照题意,先循环一遍链表,得到链表的长度,然后除以 2 之后再循环一遍,得到链表后面的部分.
/** | |
* Definition for singly-linked list. | |
* class ListNode { | |
* val: number | |
* next: ListNode | null | |
* constructor(val?: number, next?: ListNode | null) { | |
* this.val = (val===undefined ? 0 : val) | |
* this.next = (next===undefined ? null : next) | |
* } | |
* } | |
*/ | |
function middleNode(head: ListNode | null): ListNode | null { | |
let num = 0; | |
let key; | |
let curr = head; | |
while(curr){ | |
curr = curr.next; | |
num ++; | |
} | |
key = Math.floor(num/2); | |
while(key--){ | |
head = head.next; | |
} | |
return head; | |
}; |
提交之后,执行用时: 68 ms , 在所有 TypeScript 提交中击败了 33.70% 的用户.
# 学习解法
看了网友的一些解法,多是采用快慢针的方式.
/** | |
* Definition for singly-linked list. | |
* class ListNode { | |
* val: number | |
* next: ListNode | null | |
* constructor(val?: number, next?: ListNode | null) { | |
* this.val = (val===undefined ? 0 : val) | |
* this.next = (next===undefined ? null : next) | |
* } | |
* } | |
*/ | |
function middleNode(head: ListNode | null): ListNode | null { | |
let fast = head; | |
let slow = head; | |
while(fast && fast.next){ | |
slow = slow.next; | |
fast = fast.next.next; | |
} | |
return slow; | |
}; |