Leecode: Reorder List(JS解答)
解题思路:用一个数组按顺序存储所有节点,让后用前后两个指针遍历数组,重构单向链表,上代码:
function reorderList(head: ListNode | null): void {
if(head == null || head.next == null) return;
let nodeList:ListNode[] = [];
while (head != null){
nodeList.push(head);
head = head.next;
}
let start:number = 0;
let end:number = nodeList.length - 1;
while (start < end){
nodeList[start].next = nodeList[end];
start++;
if(start == end) break;
nodeList[end].next = nodeList[start];
end--;
}
nodeList[start].next = null; //最后一个节点的next为空
};