Given the head of a singly linked list, reverse the list, and return the reversed list.
LeetCode-206: Given the head of a singly linked list, reverse the list, and return the reversed list.
For each node, we need to reverse the pointer to the previous node. We also need to keep track of the next node to avoid losing the reference to the next node.
prev
to null
.public ListNode reverseList(ListNode head) {
ListNode prev = null;
while(null != head){
ListNode temp = head.next;
head.next = prev;
prev = head;
head = temp;
}
return prev;
}
The time complexity for this approach is \(O(n)\) as we are iterating over the linked list once. The space complexity is \(O(1)\) as we are using a constant amount of space for storing the temporary reference.
Be notified of new posts. Subscribe to the RSS feed.