Delete a Node in java

Delete a Node in java

We are given an integer n denoting size of linked list and after than we are given n elements where the ith element denotes the ith element if linked list (0<= i <= n-1). The head of Linked list is at position 0 and we are given a postion (0 index based), which denotes the position of element we want to delete. Delete the required node and then print the whole linked list.

Input

The first line of input contains an integer n, the number of elements in the linked list. Each of the next n lines contains an integer, the node data values in order. The last line contains an integer, position , the position of the node to delete. (0 <= position <= n-1)

Output

Output elements of linked list after deleting the required node

Constraints:

1 <= n <= 1000 1 <= llist[i] <= 1000, Where llist[i] is the ith element of linked list

Example

llist = 0 -> 1 -> 2 -> 3 position = 2 After removing node at position 2 llist = 0 -> 1 -> 3

Sample Input:

8
20
6
2
19
7
4
15
9
3

Sample Output:

20 6 2 7 4 15 9

Solution:–

import java.util.*;
import java.lang.*;
import java.io.*;



public class Main
{
  
class Node
{
  int data;
  Node next;

  Node(int x)
  {
      data=x;
      next=null;
  }
}

  Node head;

  void addLast(int x)
  {
    Node temp=head;
    Node newNode = new Node(x);
     if(head==null)
     {
        head=newNode;
        return;
     }

    while(temp.next!=null)
      {
         temp=temp.next;
      }
     temp.next=newNode;
    return;
  }

  void deleteMiddle(int k)
  {
    Node temp=head;
     if(k==0)
     {
       head=head.next;
        return ;
     }

    int i=0;
    Node demo=null;
    while(i<k &&temp.next!=null)
      {
         demo=temp;
         temp=temp.next;
        i++;
      }
    demo.next=temp.next;
    return ;
  }

  void printList()
  {
     
    if(head==null)
    {
      return;
    }
    Node temp=head;
    while(temp!=null)
      {
         System.out.print(temp.data+" ");
         temp=temp.next;
      }
    System.out.println();
  }

  
	public static void main (String[] args) throws java.lang.Exception
	{
		//your code here
       Scanner sc = new Scanner(System.in);
       int n = sc.nextInt();
       Main m1 = new Main();
       for(int i=0;i<n;i++)
         {
            int value=sc.nextInt();
            m1.addLast(value);  
         }

      int b=sc.nextInt();

      m1.deleteMiddle(b);
      m1.printList();
	}
}

Add a Comment

Your email address will not be published. Required fields are marked *