Description
Given the head of a singly linked list, reverse the list, and return the reversed list.
Examples
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,要用iterative和recursive两种方法做,iterative的方法很好像,类似于插入排序,每次都提取后面的一个node,挪到开始位置就好了。
recursive的方法感觉还需要写一下,放在一个函数里进行,终止条件是当前node或者node.next是null,然后先运行后续的节点交换,再交换当前node,举个例子来说,假设是
1 → 2 → 3 → 4 → 5
- 处理1:
- 处理2 :
- 处理3:
- 处理4:
- 处理5: 5
- 现有:4.next = (处理5中的)5
- 令:(处理5中的)5.next = 4
- 令:4.next = null
- 处理4:5 → 4
- 处理4:
- 现有:3.next = (处理4中的)4
- 令:(处理4中的)4.next = 3
- 令:3.next = null
- 处理3:5 → 4 → 3
- 处理3:
- 现有:2.next = (处理3中的)3
- 令:(处理3中的)3.next = 2
- 令:2.next = null
- 处理2:5 → 4 → 3 → 2
- 处理2 :
- 现有:1.next = (处理2中的)2
- 令:(处理2中的)2.next = 1
- 令:1.next = null
- 处理1:5 → 4 → 3 → 2 → 1
代码
iterative
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode start = new ListNode();
ListNode tmp = head;
while(tmp != null) {
ListNode next = tmp;
tmp = tmp.next;
next.next = start.next;
start.next = next;
}
return start.next;
}
}
recursive
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}