Description,
Reverse a singly linked list.
link
O(n) time complexity O(n) space complexity solution
Algorithm:
It is like a post-order tree traversal.
Assume from node k+1 to m had been reversed and you are at node k.
node(1) → … → node(k-1) → node(k) → node(k+1) ← … ← node(m)
We want node(k+1)’s next node to point to node(k).
So,
k.next.next = k;
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def __init__(self):
self.dummy = None
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
:runtime: 58ms
:spaceComplexity: O(n) -- stack cost
"""
self.traverse(head)
return self.dummy
def traverse(self, head):
if not head or not head.next:
self.dummy = head
return head
nxtNode = self.traverse(head.next)
nxtNode.next = head
head.next = None
return head
Runtime: 58ms
More usual, yet better O(1) space complexity solution
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null, cur = head;
while (cur != null) {
ListNode nxt = cur.next;
cur.next = prev;
prev = cur;
cur = nxt;
}
return prev;
}
}
Runtime: 0ms