跳到主要内容

链表

手写链表反转?

class ListNode {
constructor(value) {
this.value = value;
this.next = null;
}
}

function reverseLinkedList(head) {
let prev = null;
let current = head;
let next = null;

while (current !== null) {
// 保存下一个节点
next = current.next;
// 反转当前节点的指针
current.next = prev;
// 移动prev和current指针
prev = current;
current = next;
}

// prev现在指向反转后的链表的头部
return prev;
}

// 创建链表
const head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);

// 打印原始链表
let current = head;
while (current !== null) {
console.log(current.value);
current = current.next;
}

// 反转链表
const newHead = reverseLinkedList(head);

// 打印反转后的链表
current = newHead;
while (current !== null) {
console.log(current.value);
current = current.next;
}

k个一组链表反转

function reverseKGroup(head, k) {
let count = 0;
let node = head;
while (node && count < k) {
node = node.next;
count++;
}
if (count === k) {
node = reverseKGroup(node, k);
while (count > 0) {
const temp = head.next;
head.next = node;
node = head;
head = temp;
count--;
}
head = node;
}
return head;
}