Article Directory
Title Description
Reverse a singly linked list.
Example:
Input: 1-> 2-> 3-> 4- > 5-> NULL
Output: 5-> 4-> 3-> 2- > 1-> NULL
Description:
Can you solve this question in two ways?
answer
Classic list title, is recursive or iterative methods.
Iterative method (java)
Ideas: In fact, the idea is not very complicated, but the narrative a bit of trouble, you can look at this illustration will be a little clearer.
Simply put, a new short, then from the original list, a split, a reversed position.
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
Complexity Analysis
- Time complexity: O (n), assuming n is the length of the list.
- Space complexity: O (1)
Recursion (java)
Ideas: The iterative method with respect to, in fact, the first thing will be a little ignorant. The idea is to use recursive thinking, after part of the list are assuming no problems, has been inverted better. (Because on the back of a recursive function), only to do processing of the current node. Let the anti-node refers to.
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;
}
- Time complexity: O (n)
- Space complexity: O (n), the use of recursion, use implicit stack space.