[Solved] Define a function that takes the head of a linked list and an integer x as arguments with Java

Define a function that takes the head of a linked list and an integer x as arguments. This function deletes the xth node from a singly linked list(index starts from 1). The function returns the head of the modified linked list. The definition of linked list has already been given to you. The program prints the modified linked list as output.

Input:

3
1 3 4
3

Output:

1 3

Solution

import java.util.*;
class Node
{
  int data;
  Node next;
  Node(int d)
  {
    data = d;
    next = null;
  }
}
class DeleteNode
{
  Node head;
  void printList(Node head)
  {
    Node temp = head;
    while (temp != null)
    {
      System.out.print(temp.data+" ");
      temp = temp.next;
    }  
    System.out.println();
  }
  public void addToTheLast(Node node) 
  {
    if (head == null) 
    {
      head = node;
    } 
    else 
    {
      Node temp = head;
      while (temp.next != null)
        temp = temp.next;
      temp.next = node;
    }
  }
  public static void main(String args[])
  {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    DeleteNode llist = new DeleteNode();
    int a1 = sc.nextInt();
    Node head = new Node(a1);
    llist.addToTheLast(head);
    for (int i = 1; i < n; i++) 
    {
      int a = sc.nextInt(); 
      llist.addToTheLast(new Node(a));
    }
    int x = sc.nextInt();
    ABCD g = new ABCD(); 
    Node result = g.deleteNode(llist.head, x);
    llist.printList(result);
  }
}
class ABCD
{
  Node deleteNode(Node head, int x)
  {
    //write your code here	
    if (head == null) {
      return null;
    }
    if (x == 1) {
      return head.next;
    }
    Node temp = head;
    for (int i = 1; i < x - 1; i++) {
      temp = temp.next;
    }
    temp.next = temp.next.next;
    return head;
  }
}

Happy Learning – If you require any further information, feel free to contact me.

Share your love
Saurav Hathi

Saurav Hathi

I'm currently studying Bachelor of Computer Science at Lovely Professional University in Punjab.

📌 Nodejs and Android 😎
📌 Java

Articles: 444

Leave a Reply

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