Write a program to swap mth and nth elements of a linked list.
Code needed in java.
Code in java programming language:
class Node
{
int Data;
Node next;
Node(int data)
{
Data = data;
next = null;
}
}
class Test
{
Node head;
public void swap(int x, int y)
{
if (x == y) return;
Node preX = null, currentX = head;
while (currentX != null && currentX.Data != x)
{
preX = currentX;
currentX = currentX.next;
}
Node preY = null, currentY = head;
while (currentY != null && currentY.Data != y)
{
preY = currentY;
currentY = currentY.next;
}
if (currentX == null || currentY == null)
return;
if (preX != null)
preX.next = currentY;
else
head = currentY;
if (preY != null)
preY.next = currentX;
else
head = currentX;
Node temp = currentX.next;
currentX.next = currentY.next;
currentY.next = temp;
}
public void push(int new_data)
{
Node new_Node = new Node(new_data);
new_Node.next = head;
head = new_Node;
}
public void print()
{
Node tNode = head;
while (tNode != null)
{
System.out.print(tNode.Data+" ");
tNode = tNode.next;
}
}
public static void main(String[] args)
{
Test linkList = new Test();
linkList.push(70);
linkList.push(60);
linkList.push(50);
linkList.push(40);
linkList.push(30);
linkList.push(20);
linkList.push(10);
System.out.print("\n Linked list :");
linkList.print();
linkList.swap(40, 30);
System.out.print("\n Sorted Linked list : ");
linkList.print();
}
}
Output Screen Shot:
Thank you................
Get Answers For Free
Most questions answered within 1 hours.