方法一 迭代
1 /** 2 * Definition for singly-linked list. 3 * function ListNode(val) { 4 * this.val = val; 5 * this.next = null; 6 * } 7 */ 8 /** 9 * @param {ListNode} head 10 * @return {ListNode} 11 */ 12 var reverseList = function(head) { 13 let prev = null; 14 let curr = head; 15 while(curr) { 16 const next = curr.next; 17 curr.next = prev; 18 prev = curr; 19 curr = next; 20 } 21 return prev; 22 };
方法二 递归
1 /** 2 * Definition for singly-linked list. 3 * function ListNode(val) { 4 * this.val = val; 5 * this.next = null; 6 * } 7 */ 8 /** 9 * @param {ListNode} head 10 * @return {ListNode} 11 */ 12 var reverseList = function(head) { 13 if(head == null || head.next == null) return head; 14 const newHead = reverseList(head.next); 15 head.next.next = head; 16 head.next = null; 17 return newHead; 18 };