Reverse Linked List
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
https://leetcode.com/problems/reverse-linked-list/
反转链表。
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 || !head.next){ 14 return head; 15 } 16 17 var res = new ListNode(-1); 18 res.next = head; 19 head = head.next; 20 res.next.next = null; 21 while(head){ 22 var tmp = head.next; 23 head.next = res.next; 24 res.next = head; 25 head = tmp; 26 } 27 28 return res.next; 29 };