// 迭代 var reverseList = function (head) { var pre = null, cur = head, next; while (cur) { next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; };
function ListNode(val, next) { this.val = (val===undefined ? 0 : val) this.next = (next===undefined ? null : next) } const list = new ListNode(1) list.next = new ListNode(2) list.next.next = new ListNode(3) list.next.next.next = new ListNode(4) list.next.next.next.next = new ListNode(5) list.next.next.next.next.next = null
let middleHead = null function reverseN(head, n) { if (n === 1) { middleHead = head.next return head } const last = reverseN(head.next, n - 1) head.next.next = head head.next = middleHead return last } console.log(reverseN(list, 3))