function Node(val) { this.val = val; this.next = null; } // 遍历链表 function traverseLinkedList(head) { let current = head; while (current !== null) { console.log(current.val); // 访问当前节点的值 current = current.next; // 移动到下一个节点 } }
// 迭代方式 function reverseLinkedList(head) { let prev = null; let current = head; while (current !== null) { let nextNode = current.next; current.next = prev; prev = current; current = nextNode; } return prev; // 新的头节点 }
// 递归方式 function reverseLinkedListRecursive(head) { if (head === null || head.next === null) { return head; } let newHead = reverseLinkedListRecursive(head.next); head.next.next = head; head.next = null; return newHead; }
var node1 = new Node(1); var node2 = new Node(2); var node3 = new Node(3); var node4 = new Node(4); var node5 = new Node(5); node1.next = node2; node2.next = node3; node3.next = node4; node4.next = node5;