Given the head
of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5] Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2] Output: [2,1]
Example 3:
Input: head = [] Output: []
Constraints:
- The number of nodes in the list is the range
[0, 5000]
. -5000 <= Node.val <= 5000
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
反转链表。
这类reverse的题不会写,会写homebrew也枉然。这题我用的是iterative的思路做的。创建一个空的指针pre。当head不为空的时候,先存住head.next,然后head.next指向pre,最后pre,head,next三个指针整体往后移动一位。代码如下,也share一个注释写的比较好的discussion。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public ListNode reverseList(ListNode head) { 3 // corner case 4 if (head == null || head.next == null) { 5 return head; 6 } 7 8 // normal case 9 ListNode pre = null; 10 while (head != null) { 11 ListNode next = head.next; 12 head.next = pre; 13 pre = head; 14 head = next; 15 } 16 return pre; 17 } 18 }
JavaScript实现
1 /** 2 * @param {ListNode} head 3 * @return {ListNode} 4 */ 5 var reverseList = function(head) { 6 // corner case 7 if (head === null || head.next === null) { 8 return head; 9 } 10 11 // normal case 12 let pre = null; 13 while (head !== null) { 14 let next = head.next; 15 head.next = pre; 16 pre = head; 17 head = next; 18 } 19 return pre; 20 };
相关题目