Leetcode: Reverse Linked List
Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
基本迭代
Time: O(N), Space: O(1)
1 class Solution { 2 public ListNode reverseList(ListNode head) { 3 if (head == null) return null; 4 ListNode p1 = head; 5 ListNode p2 = head.next; 6 while (p2 != null) { 7 ListNode next = p2.next; 8 p2.next = p1; 9 p1 = p2; 10 p2 = next; 11 } 12 head.next = null; 13 return p1; 14 } 15 }
基本递归
Time: O(N), Space: O(N)递归栈大小
1 class Solution { 2 public ListNode reverseList(ListNode head) { 3 if (head == null) return null; 4 List<ListNode> res = new ArrayList<>(); 5 res.add(null); 6 reverse(head, res); 7 return res.get(0); 8 } 9 10 public ListNode reverse(ListNode node, List<ListNode> res) { 11 if (node.next == null) { 12 res.set(0, node); 13 return node; 14 } 15 ListNode afterReverse = reverse(node.next, res); 16 afterReverse.next = node; 17 node.next = null; 18 return node; 19 } 20 }