import java.util.*;
public class Main
{
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
stack.pop();
System.out.println(stack);
}
}
Stack using LL
public class Main
{
static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
next = null;
}
}
static class Stack {
public static Node head;
public static boolean isEmpty() {
return head==null;
}
public static void push(int data) {
Node newNode = new Node(data);
if(isEmpty()) {
head = newNode;
return;
}
newNode.next = head;
head=newNode;
}
public static int pop() {
if(isEmpty()) {
return -1;
}
int top = head.data;
head=head.next;
return top;
}
public static int peek() {
if(isEmpty()) {
return -1;
}
int top = head.data;
return top;
}
}
public static void main(String[] args) {
Stack s = new Stack();
// push
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.pop();
while(!s.isEmpty()) {
System.out.println(s.peek());
s.pop();
}
}
}
Stack using ArrayList
import java.util.*;
public class Main
{
static class Stack {
static ArrayList<Integer> list = new ArrayList<>();
public static boolean isEmpty() {
return list.size()==0;
}
public static void push(int data) {
list.add(data);
}
public static void pop() {
if(isEmpty()) {
System.out.println("Empty!");
}
list.remove(list.size()-1);
}
public static int peek() {
if(isEmpty()) {
return -1;
}
int top = list.get(list.size()-1);
return top;
}
}
public static void main(String[] args) {
Stack s = new Stack();
// push
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.pop();
while(!s.isEmpty()) {
System.out.println(s.peek());
s.pop();
}
}
}
Push At Bottom (Question)
import java.util.*;
public class Main
{
public static void main(String[] args) {
Stack<Integer> s = new Stack<>();
s.push(1);
s.push(2);
s.push(3);
pushAtBottom(4, s);
while(!s.isEmpty()) {
System.out.println(s.peek());
s.pop();
}
}
public static void pushAtBottom(int data, Stack<Integer> s) {
if(s.isEmpty()) {
s.push(data);
return;
}
// remove top element
int top = s.pop();
pushAtBottom(data, s);
s.push(top);
}
}