In: Computer Science
Suppose a linklist consists of more than 50 node, write a code to delete the tail node
in java
java code
class Node
{
int data;
Node next;
public Node(int data)
{
this.data=data;
}
public static void deletetail(Node head)
{
Node current = head;
while(current!=null)
{
if(current.next.next==null)
{
current.next=null;
break;
}
current=current.next;
}
}
public static void display(Node head)
{
Node current=head;
while(current!=null)
{
System.out.print(current.data+" ");
current=current.next;
}
System.out.println("");
}
}
public class Main
{
public static void main(String[] args) {
//Test for 3 nodes
Node n1=new Node(45);
Node n2=new Node(40);
Node n3=new Node(50);
n1.next=n2;
n1.next.next=n3;
n1.display(n1);
n1.deletetail(n1);
n1.display(n1);
//Test for more than 50 nodes
Node head1=new Node(1);
Node current=head1;
for(int i=0; i<55; i++)
{
current.next = new Node(i);
current=current.next;
}
head1.display(head1);
head1.deletetail(head1);
head1.display(head1);
}
}
Sample output
45 40 50 45 40 1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53