Reverse Linked List
Reverse a singly 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?
(Iterative)
Time complexity : O(n). Assume that n is the list's length, the time complexity is O(n)
Space complexity : O(1).
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null){
return head;
}
ListNode pre = null;
ListNode next = null;
ListNode cur = head;
while(cur != null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
(Recursive)
Time complexity : O(n). Assume that is the list's length, the time complexity is O(n).
Space complexity : O(n). The extra space comes from implicit stack space due to recursion. The recursion could go up to n levels deep.
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode p = reverseList(head.next);
head.next.next= head;
head.next = null;
return p;
}
Last updated