In: Computer Science
Suppose a linklist consists of more than 50 node, write a code to delete the tail node
(IN JAVA)
Tail node means the last node of linked list.
Java Code:
public class Delete_last_node {
   // this class represent a node in single linked
list.
   static class Node {
       int data;
       Node next;
   };
// this function used to insert a node at the beginning at the
linked list
   static Node add_Node_At_Beginning(Node head, int
new_data)
   {
       Node NewNode = new Node();
       NewNode.data = new_data;
       NewNode.next = head;
       head = NewNode;
       return head;
   }
// this funcion will delete the tail node
   static Node Delete_tail_node(Node head)
   {
   //if head==null , that means no node exists ,then we
just return null
       if (head == null)
           return
null;
// if only one node exists
       if (head.next == null) {
           return
null;
       }
//temp is a variable which is used to find second last(tail)
node
       Node temp = head;
       while (temp.next.next !=
null)
       {
           temp =
temp.next;
       }
//NOW(after while loop) temp is holding second last node.
//now we will make temp.next=null to delete the tail node
       temp.next = null;
       return head;
   }
   public static void main(String args[])
   {
  
// here we create a sample linked iist to test our program
Node head = null;
       head = add_Node_At_Beginning(head,
50);
       head = add_Node_At_Beginning(head,
40);
       head = add_Node_At_Beginning(head,
30);
       head = add_Node_At_Beginning(head,
20);
       head = add_Node_At_Beginning(head,
10);
       Node temp=head;
System.out.print("linked list is: ");
  
// this while loop will print the linked list
while(temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
// now using Delete_tail_node() method we delete the tail node
.
// then again we will print the linked list
       head =
Delete_tail_node(head);
System.out.println("Deleting the tail node ");
   temp=head;
System.out.print("Now the linked list is: ");   
while(temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
  
   }
}
Code In my complier:



Output:
