A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

Write a Java program to delete a specified node in the middle of a singly linked list
Q:

Write a Java program to delete a specified node in the middle of a singly linked list

0

 Write a Java program to delete a specified node in the middle of a singly linked list

Sample Singly linked list: 10->20->30->40->50
Delete the fourth node i.e. 40
Result: 10->20->30->50
Expected Output:

Original Linked list:
10->20->30->40->50
After deleting the fourth node, Linked list becomes:
10->20->30->50

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

import java.util.*;
import java.util.Arrays;
import java.util.LinkedList;

public class Solution {
 public static ListNode head = new ListNode(10);

 public static void main(String[] args) {
  head.next = new ListNode(20);
  head.next.next = new ListNode(30);
  head.next.next.next = new ListNode(40);
  head.next.next.next.next = new ListNode(50);
  ListNode p = head;
  System.out.println("Original Linked list:");
  printList(p);
  System.out.println("\nAfter deleting the fourth node, Linked list becomes:");
  deleteNode(head.next.next.next);
  p = head;
  printList(p);
 }

 public static void deleteNode(ListNode node) {
  if (node.next != null) {
   int temp = node.val;
   node.val = node.next.val;
   node.next.val = temp;

   node.next = node.next.next;
  } else {
   ListNode p = head;
   while (p.next.val != node.val) {
    p = p.next;
   }
   p.next = null;
  }
 }

 static void printList(ListNode p) {

  while (p != null) {
   System.out.print(p.val);
   if (p.next != null) {
    System.out.print("->");
   }
   p = p.next;
  }
 }
}
class ListNode {
 int val;
 ListNode next;

 ListNode(int val) {
  this.val = val;
  this.next = null;
 }
}

Sample Output:

Original Linked list:
10->20->30->40->50
After deleting the fourth node, Linked list becomes:
10->20->30->50

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now