In: Computer Science
Using Java programming,
Write a LinkedList method swap() that takes two ints as arguments and swaps the elements at those two positions.
The method should not traverse the list twice to find the elements, and it should not create or destroy any nodes.
import java.io.*;
import java.util.Scanner;
public class LinkedList {
Node head; // head of list
// Linked list Node.
//structure of a node of link list
static class Node {
int data;
Node next;
// Constructor
Node(int d)
{
data = d;
next = null;
}
}
// Method to insert a new node
public static LinkedList insert(LinkedList list, int data)
{
// Create a new node with given data
Node new_node = new Node(data);
new_node.next = null;
// If the Linked List is empty,
// then make the new node as head
if (list.head == null) {
list.head = new_node;
}
else {
// Else traverse till the last node
// and insert the new_node at the end
Node last = list.head;
while (last.next != null) {
last = last.next;
}
last.next = new_node;
}
// Return the list
return list;
}
// Method to print the LinkedList.
public static void printList(LinkedList list)
{
Node currNode = list.head;
System.out.print("LinkedList: ");
// Traverse through the LinkedList
while (currNode != null) {
// Print the data at current node
System.out.print(currNode.data + " ");
// Go to next node
currNode = currNode.next;
}
}
// Method to SWAP TWO VALUES
public static void swap(int m,int n,LinkedList list)
{
Node currNode = list.head;
Node two = list.head;
int temp,opt=0;
while (currNode != null) {
//compare the linklist data with the given two numbers
if(m==currNode.data ||n==currNode.data)
{
if(opt==1)
//second time match
break;
if(opt==0) //first time match
{
opt=1; //set the two pointer at current node
two=currNode;
}
}
// Go to next node
currNode = currNode.next;
}
//swap the two data
temp=two.data;
two.data=currNode.data;
currNode.data=temp;
}
// Driver code
public static void main(String[] args)
{
int n,no,a,b,i;
LinkedList list = new LinkedList();
Scanner scan = new Scanner(System.in);
System.out.println("Enter how many elements to be stored in Linked
List");
n=scan.nextInt();
for(i=1;i<=n;i++)
{
System.out.println("Enter a number");
no=scan.nextInt();
list = insert(list, no);
}
// Print the LinkedList
printList(list);
//ask for two numbers to swap
System.out.println("Enter a two numbers to swap");
a=scan.nextInt();
b=scan.nextInt();
//swap the two numbers
swap(a,b,list);
//display the list after swap
printList(list);
}
}
OUTPUT