Write a Java program of swap two elements in a linked list

Java Collection, LinkedList Exercises: Swap two elements in a linked list

Last update on December 14 2021 10:51:39 [UTC/GMT +8 hours]

How to Swap Two Elements in a LinkedList in Java?

Given a Linked List, the task is to swap two elements without disturbing their links. There are multiple ways to swap. Elements can be swapped using by swapping the elements inside the nodes, and by swapping the complete nodes.

Example:

Input :- 10->11->12->13->14->15 element1 = 11 element2 = 14 Output :- 10->14->12->13->11->15

Method 1: Using the in-built set method

Swap the two elements in a Linked List using the Java.util.LinkedList.set[] method. In order to achieve our desired output, first, make sure that both the elements provided to us are available in the Linked List. If either of the elements is absent, simply return. Use the set[] method to set the element1’s position to element2’s and vice versa.

Below is the code for the above approach:



Java




// Swapping two elements in a Linked List in Java
import java.util.*;
class GFG {
public static void main[String[] args]
{
LinkedList ll = new LinkedList[];
// Adding elements to Linked List
ll.add[10];
ll.add[11];
ll.add[12];
ll.add[13];
ll.add[14];
ll.add[15];
// Elements to swap
int element1 = 11;
int element2 = 14;
System.out.println["Linked List Before Swapping :-"];
for [int i : ll] {
System.out.print[i + " "];
}
// Swapping the elements
swap[ll, element1, element2];
System.out.println[];
System.out.println[];
System.out.println["Linked List After Swapping :-"];
for [int i : ll] {
System.out.print[i + " "];
}
}
// Swap Function
public static void swap[LinkedList list,
int ele1, int ele2]
{
// Getting the positions of the elements
int index1 = list.indexOf[ele1];
int index2 = list.indexOf[ele2];
// Returning if the element is not present in the
// LinkedList
if [index1 == -1 || index2 == -1] {
return;
}
// Swapping the elements
list.set[index1, ele2];
list.set[index2, ele1];
}
}


Output Linked List Before :- 10 11 12 13 14 15 Linked List After :- 10 14 12 13 11 15

Time Complexity: O[N], where N is the length of Linked List

Method 2: Using our very own Linked List

Given a linked list, provided with two values, and swap nodes for two given nodes.

Below is the implementation of the above approach:

Java




// Java Program to Swap Two Elements in a LinkedList
class Node {
int data;
Node next;
Node[int d]
{
data = d;
next = null;
}
}
class LinkedList {
Node head; // head of list
// Function to swap Nodes x and y in
// linked list by changing links
public void swapNodes[int x, int y]
{
// Nothing to do if x and y are same
if [x == y]
return;
// Search for x [keep track of prevX and CurrX]
Node prevX = null, currX = head;
while [currX != null && currX.data != x] {
prevX = currX;
currX = currX.next;
}
// Search for y [keep track of prevY and currY]
Node prevY = null, currY = head;
while [currY != null && currY.data != y] {
prevY = currY;
currY = currY.next;
}
// If either x or y is not present, nothing to do
if [currX == null || currY == null]
return;
// If x is not head of linked list
if [prevX != null]
prevX.next = currY;
else // make y the new head
head = currY;
// If y is not head of linked list
if [prevY != null]
prevY.next = currX;
else // make x the new head
head = currX;
// Swap next pointers
Node temp = currX.next;
currX.next = currY.next;
currY.next = temp;
}
// Function to add Node at beginning of list.
public void push[int new_data]
{
// 1. alloc the Node and put the data
Node new_Node = new Node[new_data];
// 2. Make next of new Node as head
new_Node.next = head;
// 3. Move the head to point to new Node
head = new_Node;
}
// This function prints contents of linked
// list starting from the given Node
public void printList[]
{
Node tNode = head;
while [tNode != null] {
System.out.print[tNode.data + " "];
tNode = tNode.next;
}
System.out.println[];
}
// Driver program to test above function
public static void main[String[] args]
{
LinkedList llist = new LinkedList[];
// The constructed linked list is:
// 1->2->3->4->5->6->7
llist.push[7];
llist.push[6];
llist.push[5];
llist.push[4];
llist.push[3];
llist.push[2];
llist.push[1];
System.out.println["Linked List Before Swapping :-"];
llist.printList[];
llist.swapNodes[4, 3];
System.out.println["Linked List After Swapping :-"];
llist.printList[];
}
}
Output Linked List Before Swapping :- 1 2 3 4 5 6 7 Linked List After Swapping :- 1 2 4 3 5 6 7


Output Linked List Before :- 1 2 3 4 5 6 7 Linked List After Swaping :- 1 2 4 3 5 6 7

Time Complexity: O[N], where N is the length of Linked List




Article Tags :
Java
Java Programs
java-LinkedList
Practice Tags :
Java
Read Full Article

Swap nodes in a linked list without swapping data

Given a linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields.

It may be assumed that all keys in the linked list are distinct.

Examples:

Input : 10->15->12->13->20->14, x = 12, y = 20 Output: 10->15->20->13->12->14 Input : 10->15->12->13->20->14, x = 10, y = 20 Output: 20->15->12->13->10->14 Input : 10->15->12->13->20->14, x = 12, y = 13 Output: 10->15->13->12->20->14

This may look like a simple problem, but is an interesting question as it has the following cases to be handled.

  1. x and y may or may not be adjacent.
  2. Either x or y may be a head node.
  3. Either x or y may be the last node.
  4. x and/or y may not be present in the linked list.

How to write a clean working code that handles all the above possibilities.



The idea is to first search x and y in the given linked list. If any of them is not present, then return. While searching for x and y, keep track of current and previous pointers. First change next of previous pointers, then change next of current pointers.

Below is the implementation of the above approach.

C++




/* This program swaps the nodes of linked list rather
than swapping the field from the nodes.*/
#include
using namespace std;
/* A linked list node */
class Node {
public:
int data;
Node* next;
};
/* Function to swap nodes x and y in linked list by
changing links */
void swapNodes[Node** head_ref, int x, int y]
{
// Nothing to do if x and y are same
if [x == y]
return;
// Search for x [keep track of prevX and CurrX
Node *prevX = NULL, *currX = *head_ref;
while [currX && currX->data != x] {
prevX = currX;
currX = currX->next;
}
// Search for y [keep track of prevY and CurrY
Node *prevY = NULL, *currY = *head_ref;
while [currY && currY->data != y] {
prevY = currY;
currY = currY->next;
}
// If either x or y is not present, nothing to do
if [currX == NULL || currY == NULL]
return;
// If x is not head of linked list
if [prevX != NULL]
prevX->next = currY;
else // Else make y as new head
*head_ref = currY;
// If y is not head of linked list
if [prevY != NULL]
prevY->next = currX;
else // Else make x as new head
*head_ref = currX;
// Swap next pointers
Node* temp = currY->next;
currY->next = currX->next;
currX->next = temp;
}
/* Function to add a node at the beginning of List */
void push[Node** head_ref, int new_data]
{
/* allocate node */
Node* new_node = new Node[];
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = [*head_ref];
/* move the head to point to the new node */
[*head_ref] = new_node;
}
/* Function to print nodes in a given linked list */
void printList[Node* node]
{
while [node != NULL] {
cout data next;
}
}
/* Driver program to test above function */
int main[]
{
Node* start = NULL;
/* The constructed linked list is:
1->2->3->4->5->6->7 */
push[&start, 7];
push[&start, 6];
push[&start, 5];
push[&start, 4];
push[&start, 3];
push[&start, 2];
push[&start, 1];
cout next;
}
// Search for y [keep track of prevY and CurrY
struct Node *prevY = NULL, *currY = *head_ref;
while [currY && currY->data != y] {
prevY = currY;
currY = currY->next;
}
// If either x or y is not present, nothing to do
if [currX == NULL || currY == NULL]
return;
// If x is not head of linked list
if [prevX != NULL]
prevX->next = currY;
else // Else make y as new head
*head_ref = currY;
// If y is not head of linked list
if [prevY != NULL]
prevY->next = currX;
else // Else make x as new head
*head_ref = currX;
// Swap next pointers
struct Node* temp = currY->next;
currY->next = currX->next;
currX->next = temp;
}
/* Function to add a node at the beginning of List */
void push[struct Node** head_ref, int new_data]
{
/* allocate node */
struct Node* new_node
= [struct Node*]malloc[sizeof[struct Node]];
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = [*head_ref];
/* move the head to point to the new node */
[*head_ref] = new_node;
}
/* Function to print nodes in a given linked list */
void printList[struct Node* node]
{
while [node != NULL] {
printf["%d ", node->data];
node = node->next;
}
}
/* Driver program to test above function */
int main[]
{
struct Node* start = NULL;
/* The constructed linked list is:
1->2->3->4->5->6->7 */
push[&start, 7];
push[&start, 6];
push[&start, 5];
push[&start, 4];
push[&start, 3];
push[&start, 2];
push[&start, 1];
printf["\n Linked list before calling swapNodes[] "];
printList[start];
swapNodes[&start, 4, 3];
printf["\n Linked list after calling swapNodes[] "];
printList[start];
return 0;
}
Java




// Java program to swap two given nodes of a linked list
class Node {
int data;
Node next;
Node[int d]
{
data = d;
next = null;
}
}
class LinkedList {
Node head; // head of list
/* Function to swap Nodes x and y in linked list by
changing links */
public void swapNodes[int x, int y]
{
// Nothing to do if x and y are same
if [x == y]
return;
// Search for x [keep track of prevX and CurrX]
Node prevX = null, currX = head;
while [currX != null && currX.data != x] {
prevX = currX;
currX = currX.next;
}
// Search for y [keep track of prevY and currY]
Node prevY = null, currY = head;
while [currY != null && currY.data != y] {
prevY = currY;
currY = currY.next;
}
// If either x or y is not present, nothing to do
if [currX == null || currY == null]
return;
// If x is not head of linked list
if [prevX != null]
prevX.next = currY;
else // make y the new head
head = currY;
// If y is not head of linked list
if [prevY != null]
prevY.next = currX;
else // make x the new head
head = currX;
// Swap next pointers
Node temp = currX.next;
currX.next = currY.next;
currY.next = temp;
}
/* Function to add Node at beginning of list. */
public void push[int new_data]
{
/* 1. alloc the Node and put the data */
Node new_Node = new Node[new_data];
/* 2. Make next of new Node as head */
new_Node.next = head;
/* 3. Move the head to point to new Node */
head = new_Node;
}
/* This function prints contents of linked list starting
from the given Node */
public void printList[]
{
Node tNode = head;
while [tNode != null] {
System.out.print[tNode.data + " "];
tNode = tNode.next;
}
}
/* Driver program to test above function */
public static void main[String[] args]
{
LinkedList llist = new LinkedList[];
/* The constructed linked list is:
1->2->3->4->5->6->7 */
llist.push[7];
llist.push[6];
llist.push[5];
llist.push[4];
llist.push[3];
llist.push[2];
llist.push[1];
System.out.print[
"\n Linked list before calling swapNodes[] "];
llist.printList[];
llist.swapNodes[4, 3];
System.out.print[
"\n Linked list after calling swapNodes[] "];
llist.printList[];
}
}
// This code is contributed by Rajat Mishra
Python




# Python program to swap two given nodes of a linked list
class LinkedList[object]:
def __init__[self]:
self.head = None
# head of list
class Node[object]:
def __init__[self, d]:
self.data = d
self.next = None
# Function to swap Nodes x and y in linked list by
# changing links
def swapNodes[self, x, y]:
# Nothing to do if x and y are same
if x == y:
return
# Search for x [keep track of prevX and CurrX]
prevX = None
currX = self.head
while currX != None and currX.data != x:
prevX = currX
currX = currX.next
# Search for y [keep track of prevY and currY]
prevY = None
currY = self.head
while currY != None and currY.data != y:
prevY = currY
currY = currY.next
# If either x or y is not present, nothing to do
if currX == None or currY == None:
return
# If x is not head of linked list
if prevX != None:
prevX.next = currY
else: # make y the new head
self.head = currY
# If y is not head of linked list
if prevY != None:
prevY.next = currX
else: # make x the new head
self.head = currX
# Swap next pointers
temp = currX.next
currX.next = currY.next
currY.next = temp
# Function to add Node at beginning of list.
def push[self, new_data]:
# 1. alloc the Node and put the data
new_Node = self.Node[new_data]
# 2. Make next of new Node as head
new_Node.next = self.head
# 3. Move the head to point to new Node
self.head = new_Node
# This function prints contents of linked list starting
# from the given Node
def printList[self]:
tNode = self.head
while tNode != None:
print tNode.data,
tNode = tNode.next
# Driver program to test above function
llist = LinkedList[]
# The constructed linked list is:
# 1->2->3->4->5->6->7
llist.push[7]
llist.push[6]
llist.push[5]
llist.push[4]
llist.push[3]
llist.push[2]
llist.push[1]
print "Linked list before calling swapNodes[] "
llist.printList[]
llist.swapNodes[4, 3]
print "\nLinked list after calling swapNodes[] "
llist.printList[]
# This code is contributed by BHAVYA JAIN
C#




// C# program to swap two given
// nodes of a linked list
using System;
class Node {
public int data;
public Node next;
public Node[int d]
{
data = d;
next = null;
}
}
public class LinkedList {
Node head; // head of list
/* Function to swap Nodes x and y in
linked list by changing links */
public void swapNodes[int x, int y]
{
// Nothing to do if x and y are same
if [x == y]
return;
// Search for x [keep track of prevX and CurrX]
Node prevX = null, currX = head;
while [currX != null && currX.data != x] {
prevX = currX;
currX = currX.next;
}
// Search for y [keep track of prevY and currY]
Node prevY = null, currY = head;
while [currY != null && currY.data != y] {
prevY = currY;
currY = currY.next;
}
// If either x or y is not present, nothing to do
if [currX == null || currY == null]
return;
// If x is not head of linked list
if [prevX != null]
prevX.next = currY;
else // make y the new head
head = currY;
// If y is not head of linked list
if [prevY != null]
prevY.next = currX;
else // make x the new head
head = currX;
// Swap next pointers
Node temp = currX.next;
currX.next = currY.next;
currY.next = temp;
}
/* Function to add Node at beginning of list. */
public void push[int new_data]
{
/* 1. alloc the Node and put the data */
Node new_Node = new Node[new_data];
/* 2. Make next of new Node as head */
new_Node.next = head;
/* 3. Move the head to point to new Node */
head = new_Node;
}
/* This function prints contents of linked list
starting from the given Node */
public void printList[]
{
Node tNode = head;
while [tNode != null] {
Console.Write[tNode.data + " "];
tNode = tNode.next;
}
}
/* Driver code */
public static void Main[String[] args]
{
LinkedList llist = new LinkedList[];
/* The constructed linked list is:
1->2->3->4->5->6->7 */
llist.push[7];
llist.push[6];
llist.push[5];
llist.push[4];
llist.push[3];
llist.push[2];
llist.push[1];
Console.Write[
"\n Linked list before calling swapNodes[] "];
llist.printList[];
llist.swapNodes[4, 3];
Console.Write[
"\n Linked list after calling swapNodes[] "];
llist.printList[];
}
}
// This code is contributed by 29AjayKumar
Javascript




// JavaScript program to swap two
// given nodes of a linked list
class Node {
constructor[val] {
this.data = val;
this.next = null;
}
}
var head; // head of list
/*
Function to swap Nodes x and y in
linked list by changing links
*/
function swapNodes[x , y] {
// Nothing to do if x and y are same
if [x == y]
return;
// Search for x [keep track of prevX and CurrX]
var prevX = null, currX = head;
while [currX != null && currX.data != x] {
prevX = currX;
currX = currX.next;
}
// Search for y [keep track of prevY and currY]
var prevY = null, currY = head;
while [currY != null && currY.data != y] {
prevY = currY;
currY = currY.next;
}
// If either x or y is not present, nothing to do
if [currX == null || currY == null]
return;
// If x is not head of linked list
if [prevX != null]
prevX.next = currY;
else // make y the new head
head = currY;
// If y is not head of linked list
if [prevY != null]
prevY.next = currX;
else // make x the new head
head = currX;
// Swap next pointers
var temp = currX.next;
currX.next = currY.next;
currY.next = temp;
}
/* Function to add Node at beginning of list. */
function push[new_data] {
/* 1. alloc the Node and put the data */
var new_Node = new Node[new_data];
/* 2. Make next of new Node as head */
new_Node.next = head;
/* 3. Move the head to point to new Node */
head = new_Node;
}
/*
This function prints contents of
linked list starting from the given Node
*/
function printList[] {
var tNode = head;
while [tNode != null] {
document.write[tNode.data + " "];
tNode = tNode.next;
}
}
/* Driver program to test above function */
/*
The constructed linked list is:
1->2->3->4->5->6->7
*/
push[7];
push[6];
push[5];
push[4];
push[3];
push[2];
push[1];
document.write[
" Linked list before calling swapNodes[]
"]
;
printList[];
swapNodes[4, 3];
document.write[
"
Linked list after calling swapNodes[]
"
];
printList[];
// This code is contributed by todaysgaurav
Output Linked list before calling swapNodes[] 1 2 3 4 5 6 7 Linked list after calling swapNodes[] 1 2 4 3 5 6 7

Optimizations: The above code can be optimized to search x and y in a single traversal. Two loops are used to keep the program simple.

Simpler approach –

C++




// C++ program to swap two given nodes of a linked list
#include
using namespace std;
// A linked list node class
class Node {
public:
int data;
class Node* next;
// constructor
Node[int val, Node* next]
: data[val]
, next[next]
{
}
// print list from this
// to last till null
void printList[]
{
Node* node = this;
while [node != NULL] {
cout data next;
}
cout data == x] {
a = head_ref;
}
else if [[*head_ref]->data == y] {
b = head_ref;
}
head_ref = &[[*head_ref]->next];
}
// if we have found both a and b
// in the linked list swap current
// pointer and next pointer of these
if [a && b] {
swap[*a, *b];
swap[[[*a]->next], [[*b]->next]];
}
}
// Driver code
int main[]
{
Node* start = NULL;
// The constructed linked list is:
// 1->2->3->4->5->6->7
push[&start, 7];
push[&start, 6];
push[&start, 5];
push[&start, 4];
push[&start, 3];
push[&start, 2];
push[&start, 1];
cout printList[];
swapNodes[&start, 6, 1];
cout printList[];
}
Java




// Java program to swap two given nodes of a linked list
public class Solution {
// Represent a node of the singly linked list
class Node {
int data;
Node next;
public Node[int data]
{
this.data = data;
this.next = null;
}
}
// Represent the head and tail of the singly linked list
public Node head = null;
public Node tail = null;
// addNode[] will add a new node to the list
public void addNode[int data]
{
// Create a new node
Node newNode = new Node[data];
// Checks if the list is empty
if [head == null] {
// If list is empty, both head and
// tail will point to new node
head = newNode;
tail = newNode;
}
else {
// newNode will be added after tail such that
// tail's next will point to newNode
tail.next = newNode;
// newNode will become new tail of the list
tail = newNode;
}
}
// swap[] will swap the given two nodes
public void swap[int n1, int n2]
{
Node prevNode1 = null, prevNode2 = null,
node1 = head, node2 = head;
// Checks if list is empty
if [head == null] {
return;
}
// If n1 and n2 are equal, then
// list will remain the same
if [n1 == n2]
return;
// Search for node1
while [node1 != null && node1.data != n1] {
prevNode1 = node1;
node1 = node1.next;
}
// Search for node2
while [node2 != null && node2.data != n2] {
prevNode2 = node2;
node2 = node2.next;
}
if [node1 != null && node2 != null] {
// If previous node to node1 is not null then,
// it will point to node2
if [prevNode1 != null]
prevNode1.next = node2;
else
head = node2;
// If previous node to node2 is not null then,
// it will point to node1
if [prevNode2 != null]
prevNode2.next = node1;
else
head = node1;
// Swaps the next nodes of node1 and node2
Node temp = node1.next;
node1.next = node2.next;
node2.next = temp;
}
else {
System.out.println["Swapping is not possible"];
}
}
// display[] will display all the
// nodes present in the list
public void display[]
{
// Node current will point to head
Node current = head;
if [head == null] {
System.out.println["List is empty"];
return;
}
while [current != null] {
// Prints each node by incrementing pointer
System.out.print[current.data + " "];
current = current.next;
}
System.out.println[];
}
public static void main[String[] args]
{
Solution sList = new Solution[];
// Add nodes to the list
sList.addNode[1];
sList.addNode[2];
sList.addNode[3];
sList.addNode[4];
sList.addNode[5];
sList.addNode[6];
sList.addNode[7];
System.out.println["Original list: "];
sList.display[];
// Swaps the node 2 with node 5
sList.swap[6, 1];
System.out.println["List after swapping nodes: "];
sList.display[];
}
}
Python3




# Python3 program to swap two given
# nodes of a linked list
# A linked list node class
class Node:
# constructor
def __init__[self, val=None, next1=None]:
self.data = val
self.next = next1
# print list from this
# to last till None
def printList[self]:
node = self
while [node != None]:
print[node.data, end=" "]
node = node.next
print[" "]
# Function to add a node
# at the beginning of List
def push[head_ref, new_data]:
# allocate node
[head_ref] = Node[new_data, head_ref]
return head_ref
def swapNodes[head_ref, x, y]:
head = head_ref
# Nothing to do if x and y are same
if [x == y]:
return None
a = None
b = None
# search for x and y in the linked list
# and store therir pointer in a and b
while [head_ref.next != None]:
if [[head_ref.next].data == x]:
a = head_ref
elif [[head_ref.next].data == y]:
b = head_ref
head_ref = [[head_ref].next]
# if we have found both a and b
# in the linked list swap current
# pointer and next pointer of these
if [a != None and b != None]:
temp = a.next
a.next = b.next
b.next = temp
temp = a.next.next
a.next.next = b.next.next
b.next.next = temp
return head
# Driver code
start = None
# The constructed linked list is:
# 1.2.3.4.5.6.7
start = push[start, 7]
start = push[start, 6]
start = push[start, 5]
start = push[start, 4]
start = push[start, 3]
start = push[start, 2]
start = push[start, 1]
print["Linked list before calling swapNodes[] "]
start.printList[]
start = swapNodes[start, 6, 1]
print["Linked list after calling swapNodes[] "]
start.printList[]
# This code is contributed by Arnab Kundu
C#




// C# program to swap two
// given nodes of a linked list
using System;
class GFG {
// A linked list node class
public class Node {
public int data;
public Node next;
// constructor
public Node[int val, Node next1]
{
data = val;
next = next1;
}
// print list from this
// to last till null
public void printList[]
{
Node node = this;
while [node != null] {
Console.Write[node.data + " "];
node = node.next;
}
Console.WriteLine[];
}
}
// Function to add a node
// at the beginning of List
static Node push[Node head_ref, int new_data]
{
// allocate node
[head_ref] = new Node[new_data, head_ref];
return head_ref;
}
static Node swapNodes[Node head_ref, int x, int y]
{
Node head = head_ref;
// Nothing to do if x and y are same
if [x == y]
return null;
Node a = null, b = null;
// search for x and y in the linked list
// and store therir pointer in a and b
while [head_ref.next != null] {
if [[head_ref.next].data == x] {
a = head_ref;
}
else if [[head_ref.next].data == y] {
b = head_ref;
}
head_ref = [[head_ref].next];
}
// if we have found both a and b
// in the linked list swap current
// pointer and next pointer of these
if [a != null && b != null] {
Node temp = a.next;
a.next = b.next;
b.next = temp;
temp = a.next.next;
a.next.next = b.next.next;
b.next.next = temp;
}
return head;
}
// Driver code
public static void Main[]
{
Node start = null;
// The constructed linked list is:
// 1.2.3.4.5.6.7
start = push[start, 7];
start = push[start, 6];
start = push[start, 5];
start = push[start, 4];
start = push[start, 3];
start = push[start, 2];
start = push[start, 1];
Console.Write[
"Linked list before calling swapNodes[] "];
start.printList[];
start = swapNodes[start, 6, 1];
Console.Write[
"Linked list after calling swapNodes[] "];
start.printList[];
}
}
/* This code contributed by PrinciRaj1992 */
Javascript




// javascript program to swap two given nodes of a linked list
// Represent a node of the singly linked list
class Node {
constructor[val] {
this.data = val;
this.next = null;
}
}
// Represent the head and tail of the singly linked list
var head = null;
var tail = null;
// addNode[] will add a new node to the list
function addNode[data] {
// Create a new node
var newNode = new Node[data];
// Checks if the list is empty
if [head == null] {
// If list is empty, both head and
// tail will point to new node
head = newNode;
tail = newNode;
} else {
// newNode will be added after tail such that
// tail's next will point to newNode
tail.next = newNode;
// newNode will become new tail of the list
tail = newNode;
}
}
// swap[] will swap the given two nodes
function swap[n1 , n2] {
var prevNode1 = null, prevNode2 = null, node1 = head, node2 = head;
// Checks if list is empty
if [head == null] {
return;
}
// If n1 and n2 are equal, then
// list will remain the same
if [n1 == n2]
return;
// Search for node1
while [node1 != null && node1.data != n1] {
prevNode1 = node1;
node1 = node1.next;
}
// Search for node2
while [node2 != null && node2.data != n2] {
prevNode2 = node2;
node2 = node2.next;
}
if [node1 != null && node2 != null] {
// If previous node to node1 is not null then,
// it will point to node2
if [prevNode1 != null]
prevNode1.next = node2;
else
head = node2;
// If previous node to node2 is not null then,
// it will point to node1
if [prevNode2 != null]
prevNode2.next = node1;
else
head = node1;
// Swaps the next nodes of node1 and node2
var temp = node1.next;
node1.next = node2.next;
node2.next = temp;
} else {
document.write["Swapping is not possible"];
}
}
// display[] will display all the
// nodes present in the list
function display[] {
// Node current will point to head
var current = head;
if [head == null] {
document.write["List is empty"];
return;
}
while [current != null] {
// Prints each node by incrementing pointer
document.write[current.data + " "];
current = current.next;
}
document.write[];
}
// Add nodes to the list
addNode[1];
addNode[2];
addNode[3];
addNode[4];
addNode[5];
addNode[6];
addNode[7];
document.write["Original list:
"];
display[];
// Swaps the node 2 with node 5
swap[6, 1];
document.write["
List after swapping nodes:
"];
display[];
// This code contributed by aashish2995
Output Linked list before calling swapNodes[] 1 2 3 4 5 6 7 Linked list after calling swapNodes[] 6 2 3 4 5 1 7

//www.youtube.com/watch?v=V4ZHvhvVmSE

This article is contributed by Gautam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




Article Tags :
Linked List
Practice Tags :
Linked List
Read Full Article

Program to swap nodes in a singly linked list without swapping data

Explanation

In this program, we need to swap given two nodes in the singly linked list without swapping data.

One of the approaches to accomplish this task is to swap the previous nodes of the given two nodes and then, swap the next nodes of two nodes.

Algorithm

  1. Create a class Node which has two attributes: data and next. Next is a pointer to the next node in the list.
  2. Create another class SwapNodes which has two attributes: head and tail.
  3. addNode[] will add a new node to the list:
    1. Create a new node.
    2. It first checks, whether the head is equal to null which means the list is empty.
    3. If the list is empty, both head and tail will point to a newly added node.
    4. If the list is not empty, the new node will be added to end of the list such that tail's next will point to a newly added node. This new node will become the new tail of the list.
  4. swap[] will swap the given two nodes present in the list:
    1. Let n1 and n2 be the values need to be swapped.
    2. If the list is empty then, return from the function.
    3. If n1 and n2 are equal then, there will be no change in the list.
    4. If the list is not empty then, search for n1 by traversing through the list such that prevNode1 which will point to node previous to node1 and node 1 will point to the node having value n1.
    5. Similarly, search for n2 by traversing through the list such that prevNode2 which will point to node previous to node2 and node 2 will point to the node having value n2.
    6. If prevNode1 points to head then, node2 will become head of the list. Similarly, if prevNode2 points to head then, node1 will become head of the list.
    7. If prevNode1 or prevNode2 is not pointing to head then, swap the nodes such that prevNode1 will become the previous node of node2 and prevNode2 will become the previous node of node1.
    8. Now, swap next nodes of node1 and node2.
  5. display[] will display the nodes present in the list:
    1. Define a node current which will initially point to the head of the list.
    2. Traverse through the list till current points to null.
    3. Display each node by making current to point to node next to it in each iteration.

Solution

Python

Output:

Original list: 1 2 3 4 5 List after swapping nodes: 1 5 3 4 2

C

Output:

Original list: 1 2 3 4 5 List after swapping nodes: 1 5 3 4 2

JAVA

Output:

Original list: 1 2 3 4 5 List after swapping nodes: 1 5 3 4 2

C#

Output:

Original list: 1 2 3 4 5 List after swapping nodes: 1 5 3 4 2

PHP

Output:

Original list: 1 2 3 4 5 List after swapping nodes: 1 5 3 4 2

“java linked list swap elements” Code Answer


java linked list swap elements
java by This is my name on Aug 12 2020 Comment
0
Add a Grepper Answer

Java answers related to “java linked list swap elements”

  • java list swap 2 elements
  • Write a java program to merge three singly linked list elements
  • java singly linked list example 2 res
  • swapping techniques using java
  • java reverse linked list

Java queries related to “java linked list swap elements”

  • how to swap elements in a linked list java
  • swap two nodes in linked list java
  • why do we use swapping linked list in java
  • swap elements in linked list
  • java swap linked list nodes
  • linkedlist swap index
  • java linked list swap order based on reference
  • can we use swap funtion in linked list
  • single linked list swap java
  • java linked list swap nodes
  • linkedlist swap neighbours java
  • swapping two nodes in a doubly linked list c
  • swap elements linked list
  • how to swap objects in linkedlist java
  • swap elements in doubly linked list java
  • swap every 2 items in linked list java
  • java swapping nodes in a doubly linked list
  • java linked list swap elements
  • how to change java list item position
  • java swap elements in linked list
  • swap elements in linked list with iterator
  • linked list swap elements java
  • linked list delete nodes java using swap
  • how to swap two elements in a linked list java
  • how to swap index in linkedlist java
  • swap items in linked list in java
  • swap kth nodes from end linked list java
  • singlylinked list swap nodes java
  • how to swap objects places linked list java
  • swap nodes in a linked list + java
  • swap the elements in linked list
  • swap data of two nodes in a link list java
  • java list change position of element
  • swap two nodes of doubly linked list in java
  • swapping two nodes in a singly linked list java
  • how to swap indexes in linkedlist java
  • linked list swap java
  • java change position in list
  • linked list swaping java without library
  • swap two linkedlist items in java
  • swapping linked list nodes java
  • swap node near in linked list java
  • single linked list swapitems java
  • java list change item position
  • swap node in linked list java
  • swap kth element linked list
  • swap nodes in a linked list java ashinf
  • how to swap elements in a linked list using java collections java
  • how to swap 2 elements in a doubly linked list c
  • how to swap nodes in a doubly linked list java
  • swap element linked list

Example:

package com.w3spoint; import java.util.Collections; import java.util.LinkedList; public class Test { public static void main[String args[]]{ LinkedList linkedList = new LinkedList[]; linkedList.add["Jai"]; linkedList.add["Mahesh"]; linkedList.add["Naren"]; linkedList.add["Vivek"]; linkedList.add["Vishal"]; linkedList.add["Hemant"]; System.out.println["Actual LinkedList:"+linkedList]; Collections.swap[linkedList, 2, 4]; System.out.println["Results after swap operation:" + linkedList]; } }

package com.w3spoint; import java.util.Collections; import java.util.LinkedList; public class Test { public static void main[String args[]]{ LinkedList linkedList = new LinkedList[]; linkedList.add["Jai"]; linkedList.add["Mahesh"]; linkedList.add["Naren"]; linkedList.add["Vivek"]; linkedList.add["Vishal"]; linkedList.add["Hemant"]; System.out.println["Actual LinkedList:"+linkedList]; Collections.swap[linkedList, 2, 4]; System.out.println["Results after swap operation:" + linkedList]; } }

Video liên quan

Bài mới nhất

Chủ Đề