Stack using Java

Mathavkrishnan S
2 min readJan 29, 2022

--

Before understanding the concept of stack, it’s better to know the operations

→Push

→Pop

→Peek

From the diagram, note stack is like a container, where you can keep on adding the elements at top and can only pop elements at top. Peek operation is used to see the top most element (eg top of element is 2 then peek gives 2).

In this blog, we will see about stack implementation using arrays and then with linked list. Don’t get panic after seeing linked list, it’s really super simple. Only you have to make small changes to convert it into stack. Now guess of converting linked list, only you have to push elements at beginning and for pop, you have to delete last node and for seeing the elements, you have to print the elements of stack in reverse.

Coming to array, it’s very simple, we are going to blow this within seconds.

Now you know the concepts of stack, so try to implement based on your understanding, then go for the code section.

Code:

class Stack {
static final int
MAX = 1000;
int
top;
int a[] = new int[MAX];

boolean isEmpty()
{
return (top < 0);
}
Stack()
{
top = -1;
}

boolean push(int x)
{
a[++top] = x;
System.out.println(x + “ “);
return true;
}
int
pop()
{
int x = a[top — ];
return x;
}

int peek()
{
int x = a[top];
return x;
}

void
print(){
for(int i = top;i>-1;i — ){
System.out.print(“ “+ a[i]);
}
}
}
class
Main {
public static void main(String args[])
{
Stack s = new Stack();
s.push(10);
s.push(20);
s.push(30);
System.out.println(s.pop() + “ Popped from stack”);
System.out.println(“Top element is :” + s.peek());
System.out.print(“Elements present in stack :”);
s.print();
}
}

Now it’s time to move to interesting part of stack, using Linked list. I assume that you already have knowledge on linked list, else hurray! I made a blog on linked list. check it out!

I’m going to show only code for this because you can understand from it.

Code:

import java.util.*;
public class Main
{
public static class Node
{
int data;
Node next;

}
public static Node head;
public static void print()
{
Node dummy = head;
while(dummy != null){
System.out.println(dummy.data);
dummy = dummy.next;
}
}
public static void pop(){
Node dummy = head;
dummy = dummy.next;
head = dummy;
}
public static void push(int data){
Node newnode = new Node();
newnode.data = data;
if(head == null){
newnode.next = null;
head = newnode;
}
else{
newnode.next = head;
head = newnode;
}
}
public static void peek(){
Node dummy = head;
System.out.println(“top : “ + dummy.data);
}
public static boolean isempty(){
return (head == null);
}
public static void main(String args[])
{
push(2);
push(5);
push(8);
print();
pop();
peek();
print();
System.out.println(isempty());
}
}

--

--