In Place Reversal of Linked List Flashcards
1
Q
206: Reverse a LinkedList
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
TC – O(n)
SC – O(1)
A
Pseudo code:
- Declare variable current which will initially point to the head of the LinkedList.
- Declare variable next, previous which will initially point to null.
- Iterate until current is not null
a. Keep next value in next variable.
b. Assign previous to current.next.
c. Reverse the current node by pointing it to the previous before moving on to the next node
d. Update the previous to the previous node that we have processed.
e. Assign next into current. - Return previous.