In this blog we will learn how to implement stack using linked list in java
class Node
{
int data;
Node next;
Node(int data)
{
this.data=data;
this.next=null;
}
}
public class LinkedListImplementation {
public static boolean isempty(Node head)
{
if(head == null)
return true;
return false;
}
public static Node push(Node head,int data)
{
Node temp=new Node(data);
temp.next=head;
return temp;
}
public static Node pop(Node head)
{
if(head==null)
return null;
if(head.next==null)
return null;
head=head.next;
return head;
}
public static void print(Node head)
{
Node curr=head;
while(curr !=null)
{
System.out.print(curr.data+" ");
curr=curr.next;
}
System.out.print("\n");
}
public static void main(String args[])
{
Node head=null;
boolean b=isempty(head);
System.out.println(b);
head=new Node(10);
b=isempty(head);
System.out.println(b);
Node temp1=new Node(20);
Node temp2=new Node(30);
head.next=temp1;
temp1.next=temp2;
print(head);
head=push(head,40);
head=push(head,50);
print(head);
head=pop(head);
print(head);
}
}