In: Computer Science
Remove the minimum element from the linked list in Java
public class LinkedList {
// The LinkedList Node class
private class Node{
int data;
Node next;
Node(int gdata)
{
this.data =
gdata;
this.next =
null;
}
}
// The LinkedList fields
Node head;
// Constructor
LinkedList(int gdata)
{
this.head = new Node(gdata);
}
public void Insertend(int gdata)
{
Node current = this.head;
while(current.next!= null)
{
current =
current.next;
}
Node newnode = new
Node(gdata);
current.next = newnode;
}
public void Listprint()
{
Node current = this.head;
while(current!= null)
{
System.out.print(current.data + " ");
current =
current.next;
}
System.out.println();
}
public void Removemin() {
// Complete this method to remove the minimum value in
a linkedlist
}
public static void main(String[] args) {
LinkedList exlist = new
LinkedList(8);
exlist.Insertend(1);
exlist.Insertend(5);
exlist.Insertend(2);
exlist.Insertend(7);
exlist.Insertend(10);
exlist.Insertend(3);
exlist.Listprint();
//output: 8 1 5 2 7 10 3
exlist.Removemin();
exlist.Listprint();
//output should be: 8 5 2 7 10
3
}
}
// do comment if any problem arises
//code
class LinkedList {
// The LinkedList Node class
private class Node {
int data;
Node next;
Node(int gdata) {
this.data = gdata;
this.next = null;
}
}
// The LinkedList fields
Node head;
// Constructor
LinkedList(int gdata) {
this.head = new Node(gdata);
}
public void Insertend(int gdata) {
Node current = this.head;
while (current.next != null) {
current = current.next;
}
Node newnode = new Node(gdata);
current.next = newnode;
}
public void Listprint() {
Node current = this.head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public void Removemin() {
// find node containing minimum element
Node temp = head;
boolean flag = true;
Node min = null;
Node current_min = temp;
while (temp.next != null) {
if (current_min.data > (temp.next).data) {
min = temp;
current_min = temp.next;
}
temp = temp.next;
}
// delete that node
if (min == null) {
head = head.next;
}
// if minimum node is some other node then simply shift next of minimun to next
// of next of minimum
else {
min.next = min.next.next;
}
}
public static void main(String[] args) {
LinkedList exlist = new LinkedList(8);
exlist.Insertend(1);
exlist.Insertend(5);
exlist.Insertend(2);
exlist.Insertend(7);
exlist.Insertend(10);
exlist.Insertend(3);
exlist.Listprint();
// output: 8 1 5 2 7 10 3
exlist.Removemin();
exlist.Listprint();
// output should be: 8 5 2 7 10 3
}
}
Output: