Reversing a Linked List Using Iteration
We will use a loop to iterate through the elements and the pointer nodes of the linked list and change the next pointers of each node in such a way that their order is reversed.
Example: The below code iteratively reverses the linked list in JavaScript.
Javascript
class Node { constructor(data, next = null ) { this .data = data; this .next = next; } } class LinkedList { constructor() { this .head = null ; } insertFirst(data) { this .head = new Node(data, this .head); } printList() { let current = this .head; while (current !== null ) { console.log(current.data); current = current.next; } } reverse() { let prev = null ; let current = this .head; let next = null ; while (current !== null ) { next = current.next; current.next = prev; prev = current; current = next; } this .head = prev; } } const linkedList = new LinkedList(); linkedList.insertFirst(3); linkedList.insertFirst(2); linkedList.insertFirst(1); console.log( "Original Linked List:" ); linkedList.printList(); linkedList.reverse(); console.log( "\nReversed Linked List:" ); linkedList.printList(); |
Output
Original Linked List: 1 2 3 Reversed Linked List: 3 2 1
Time Complexity: O(N)
Space Complexity: O(1)
JavaScript Program to Reverse a Linked List
A linked list is a data structure where elements are stored in nodes, and each node points to the next node in the sequence. Reversing a linked list involves changing the direction of the pointers, making the last node the new head and the head the new tail.
Below are the approaches to reverse a linked list in JavaScript:
Table of Content
- Reversing a Linked List Using Iteration
- Reversing a Linked List Using Recursion
Contact Us