如何反转一个链表
三个指针,一个指向头节点,另外两个用来指向头节点前后两个节点的位置
javascript
// 定义链表节点类
class ListNode {
constructor(val) {
this.val = val;
this.next = null;
}
}
// 定义反转链表函数
function reverseLinkedList(head) {
let prev = null;
let current = head;
while (current !== null) {
const nextTemp = current.next;
current.next = prev;
prev = current;
current = nextTemp;
}
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);
console.log("原始链表:");
let current = head;
while (current !== null) {
console.log(current.val);
current = current.next;
}
const reversedHead = reverseLinkedList(head);
console.log("反转后的链表:");
let reversedCurrent = reversedHead;
while (reversedCurrent !== null) {
console.log(reversedCurrent.val);
reversedCurrent = reversedCurrent.next;
}