Section 3 - JAVA Coding-15 mins
Delete middle of linked list
Given a singly linked list, delete middle of the linked list. For example, if given linked list is 1->2
should be modified to 1->2->4->5
If there are even nodes, then there would be two middle nodes, we need to delete the seco
example, if given linked list is 1->2->3->4->5->6 then it should be modified to 1->2->3>5->
If the input linked list is NULL, then it should remain NULL
If the input linked list has 1 node, then this node should be deleted and new head shoul
warê şervices
Answers
LinkedList Modifications - Java
Since we do not know any sort of info about the list, we will ask the user for number of elements in the list, and then also input each element.
We will be using LinkedList of the type <String> to allow for all possible elements.
Once we have all the inputs, we can display the original list once.
After that, we take the size of the list by the LinkedList.size() method and divide it by 2.
The integer division process makes sure we get the required index number. We then simply use the remove(index) method to remove the middle element as required.
Print out the final list then.
Here goes the code.
import java.util.*;
public class LinkedLists
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//Ask user for number of elements in list
System.out.print("Enter the number of elements in the list: ");
int n = sc.nextInt(); //Store in variable n
if(n == 0) //If n = 0, list is Null. Exit program.
{
System.out.println("List is NULL");
System.exit(0);
}
sc.nextLine(); //Required to flush any line input above
//Create Linked List of type String
LinkedList<String> myList = new LinkedList<String>();
//Run a loop to take user input of list elements
for(int i = 0; i < n; i++)
{
System.out.print("Enter the element no. "+(i+1)+": ");
myList.add(sc.nextLine());
}
//Print out the Original List once
System.out.println("Original List:\n"+myList);
int length = myList.size(); //Store size of list in variable length
//Simple division by 2 gives us the index to remove
int indexToRemove = length/2;
//Remove the middle element
myList.remove(indexToRemove);
System.out.println("Middle Element now removed.");
System.out.println("New List: \n"+myList); //Print out new list
}
}