1.重排链表
题目:
给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
思路:先放进数组里,用数组下标去获取节点
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {void} Do not return anything, modify head in-place instead.
*/
var reorderList = function(head) {
const list = [];
while (head) {
list.push(head);
head = head.next;
}
const pre = new ListNode();
let node = pre;
let count = 0;
while (list.length) {
if (count % 2) {
node.next = list.pop();
} else {
node.next = list.shift();
}
node = node.next;
count++;
}
node.next=null
return pre.next;
};
可以考虑优化。看新链表的节点顺序,可以从中间截断,分成两个链表,然后后半部分的链表倒置,最后左右链表依次取第一个节点拼接
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {void} Do not return anything, modify head in-place instead.
*/
var reorderList = function(head) {
const dummy = new ListNode(0)
dummy.next = head
let slow = dummy
let quick = dummy
while (quick && quick.next) {
slow = slow.next
quick = quick.next
quick = quick.next
}
let right = slow.next
slow.next = null
let left = dummy.next
right = reverseList(right)
while (left && right) {
let lNext = lef