# Swap nodes in linked list without swapping its data

367 views
Swap two nodes in linked list without swapping its data in java.

Input = [40 80 30 20 10]
Output = [40 20 30 80 10]

by (5k points)
See the following running code for swiping two nodes in given linked list:-

public class Node<T> {

private T data;
private Node<T> next;

public Node(){
setData(null);
setNext(null);
}

public Node(T data){
setData(data);
setNext(null);
}

public T getData(){
return data;
}

public void setData(T data){
this.data = data;
}

public Node<T> getNext(){
return next;
}

public void setNext(Node<T> next){
this.next = next;
}

}

import java.util.HashMap;

if(data == null){
return;
}
}else{
Node<T> newNode = new Node<T>(data);
}
}
/**
* @param x
* @param y
*
* Swap node x and y in linked list by changing reference
*
* Following points to be considered in this program:-
* 1. Both are not same
* 2. Both are present in linked list
* 3. Both are adjacent node
* 4. Either x or y is head node
* 5. Either x or y is last node

*/

public void doSwapNode(T x, T y){
//Both are same data then no need to swap
if(x == y){
return;
}
//Find x in list
Node<T> currX = head, prevX = null;
while(currX != null && currX.getData() != x){
prevX = currX;
currX = currX.getNext();
}

//Find y in list
Node<T> currY = head, prevY = null;
while(currY != null && currY.getData() != y){
prevY = currY;
currY = currY.getNext();
}

//Check either x or y is not exists in list
if(currX == null || currY == null){
return;
}

//x is either head node or other node
if(prevX == null){
}else{
prevX.setNext(currY);
}
if(prevY == null){
}else{
prevY.setNext(currX);
}
//Swap next reference
Node<T> temp = currX.getNext();
currX.setNext(currY.getNext());
currY.setNext(temp);
}
}

/**
* @param args
*/
public static void main(String[] args) {