Basics and Reverse A Linked List
Basics and Reverse A Linked List
Question

Given a linked list, return it in reverse.
Verify the constraints
- What do we return if we get null or a single node? - Just return null and the node back respectively.
Write out some test cases
- 1,2,3,4,5,null => 5,4,3,2,1,null
- 1 => 1
- null => null
Figure out a solution without code
- We won't know the full length of the linked list unless we traverse it! - so we have to implement iterative technique
Write out our solution in code
class ListNode{
constructor(val, next = null){
this.val = val;
this.next = next;
}
}
const linkedList = [5,4,3,2,1].reduce((acc, val) => new ListNode(val, acc), null);
const printList = (head) => {
let result = "";
let curNode = head;
while (curNode !== null) {
result += curNode.val + "--> ";
curNode = curNode.next;
}
return result;
}
function getReversedLinkedList(head){
let curNode = head;
let prevNode = null;
while(curNode){
const next = curNode.next;
curNode.next = prevNode;
prevNode = curNode;
curNode = next;
}
head = prevNode;
return head;
}
console.log(printList(linkedList));
console.log(printList(getReversedLinkedList(linkedList)))
Analyze Space and Time Complexity
- Time Complexity: O(N)
- Space Complexity: O(1)
Developing References
Developing Report
2025-01-23 - Basics and Reverse A Linked List Report
2025-01-23 - Developing Daily Report
2025-01-4th - Developing Weekly Report