JavaScript Program to Swap Two Elements in a Linked List
Last Updated :
12 Mar, 2024
We are given a linked list and the task is to swap two elements in a linked list without disturbing their links. There are multiple ways to swap. It can be done by swapping the elements inside the nodes, and by swapping the complete nodes.
Example:
Input: list = 10 -> 11 -> 12 -> 13 -> 14 -> 15
ele1 = 11
ele2 = 14
Output: list = 10 -> 14 -> 12 -> 13 -> 11 -> 15
Below are the ways by which we can swap two elements in a linked list in JavaScript.
Using Recursion
The approach is to use the recursive nature of JavaScript functions to traverse the linked list and swap the elements.
Algorithm:
- Define a Node class with attributes data and next to represent each element of the linked list.
- Define a LinkedList class with a constructor to initialize the head of the linked list.
- Implement a method insert(data) to insert a new node at the end of the linked list.
- Implement a recursive method swapUtil(current, x, y):
- If the current node is null, return.
- If the data of the current node equals x, set its data to y.
- If the data of the current node equals y, set its data to x.
- Recursively call swapUtil with the next node as the current node.
- Implement a method swap(x, y):
- If x and y are the same, return.
- Call swapUtil with the head of the linked list, x, and y.
- Implement a method
printList()
to print the elements of the linked list
Example: This example shows the use of the above-explained approach.
JavaScript
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
// Function to insert a new node at
// the end of the linked list
insert(data) {
const newNode = new Node(data);
if (!this.head) {
this.head = newNode;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
}
// Function to swap two elements in the
// linked list using recursion
swapUtil(current, x, y) {
if (!current) return;
if (current.data === x) {
current.data = y;
} else if (current.data === y) {
current.data = x;
}
this.swapUtil(current.next, x, y);
}
swap(x, y) {
if (x === y) return;
this.swapUtil(this.head, x, y);
}
// Function to print the linked list
printList() {
let current = this.head;
while (current) {
console.log(current.data);
current = current.next;
}
}
}
// Example usage:
const linkedList = new LinkedList();
linkedList.insert(10);
linkedList.insert(11);
linkedList.insert(12);
linkedList.insert(13);
linkedList.insert(14);
linkedList.insert(15);
console.log("Before swapping:");
linkedList.printList();
linkedList.swap(12, 14);
console.log("After swapping:");
linkedList.printList();
OutputBefore swapping:
10
11
12
13
14
15
After swapping:
10
11
14
13
12
15
Time Complexity: O(n) where n is the number of nodes in the linked list.
Space Complexity: O(1) because it uses a constant amount of extra space regardless of the size of the input linked list.
Using Iteration
The approach here is to define traditional linked list structure with a Node
class representing each element and a LinkedList
class to manage the list. It iteratively traverses the list to find the nodes containing the given data values and adjusts their pointers to swap positions.
Algorithm:
- Define a Node class to represent each element in the linked list with a data field and a next pointer.
- Define a LinkedList class with a head pointer initially set to null.
- Implement an append method to add elements to the end of the linked list.
- Implement a printList method to print the elements of the linked list.
- Implement a swapNodes method that takes two data values to swap.
- Traverse the linked list to find the nodes containing the given data values.
- Swap the positions of the nodes by adjusting their next pointers and the pointers of their previous nodes.
- Print the updated list.
Example: This example shows the use of the above-explained approach.
JavaScript
// Node class to define the structure of
// each node in the linked list
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Linked List class to define the linked
// list and methods to operate on it
class LinkedList {
constructor() {
this.head = null;
}
// Function to add a new node at the end of the linked list
append(data) {
let newNode = new Node(data);
if (!this.head) {
this.head = newNode;
return;
}
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
// Function to print the linked list
printList() {
let current = this.head;
while (current) {
console.log(current.data);
current = current.next;
}
}
// Function to swap two elements in the linked list
swapNodes(data1, data2) {
// If both data are the same, nothing to do
if (data1 === data2) {
return;
}
let prevX = null,
currX = this.head;
while (currX && currX.data !== data1) {
prevX = currX;
currX = currX.next;
}
let prevY = null,
currY = this.head;
while (currY && currY.data !== data2) {
prevY = currY;
currY = currY.next;
}
// If either data is not present, nothing to do
if (!currX || !currY) {
return;
}
// If data1 is not the head of the linked list
if (prevX) {
prevX.next = currY;
} else {
this.head = currY;
}
// If data2 is not the head of the linked list
if (prevY) {
prevY.next = currX;
} else {
this.head = currX;
}
// Swap next pointers
let temp = currX.next;
currX.next = currY.next;
currY.next = temp;
}
}
// Example usage
let ll = new LinkedList();
ll.append(10);
ll.append(11);
ll.append(12);
ll.append(13);
ll.append(14);
ll.append(15);
console.log("Linked List Before Swapping:");
ll.printList();
ll.swapNodes(11, 14);
console.log("\nLinked List After Swapping:");
ll.printList();
OutputLinked List Before Swapping:
10
11
12
13
14
15
Linked List After Swapping:
10
14
12
13
11
15
Time Complexity: O(n) for traversing the list to find the nodes to swap and O(1) for swapping them.
Space Complexity: O(1)
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read