import java.util.ArrayList;
// LL implementation of stack
public class StackB {
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
static class Stack {
static Node head = null;
public static boolean isEmpty() {
return head == null;
}
// push - add elements on top - O(1)
public static void push(int data) {
Node newNode = new Node(data);
if(isEmpty()) {
head = newNode;
return;
}
newNode.next = head;
head = newNode;
}
// pop - delete from top - O(1)
public static int pop(){
if(isEmpty()) {
return -1;
}
int top = head.data;
head = head.next;
return top;
}
// peek - view the element from the top - O(1)
public static int peek() {
if(isEmpty()) {
return -1;
}
return head.data;
}
}
public static void main(String[] args) {
Stack s = new Stack();
s.push(1);
s.push(2);
s.push(3);
while(!s.isEmpty()) {
System.out.println(s.peek());
s.pop();
}
}
}
No comments:
Post a Comment