stack implementation in java code example
Example 1: java stack
Stack<String> stack = new Stack<String>();
stack.push("Hello");
String top = stack.pop();
String peek = stack.peek();
Example 2: java stack methods
import java.util.Stack<E>;
Stack<Integer> myStack = new Stack<Integer>();
myStack.push(1);
myStack.pop();
myStack.peek();
myStack.empty();
Example 3: stack in java
import java.io.*;
import java.util.*;
class Test
{
static void stack_push(Stack<Integer> stack)
{
for(int i = 0; i < 5; i++)
{
stack.push(i);
}
}
static void stack_pop(Stack<Integer> stack)
{
System.out.println("Pop Operation:");
for(int i = 0; i < 5; i++)
{
Integer y = (Integer) stack.pop();
System.out.println(y);
}
}
static void stack_peek(Stack<Integer> stack)
{
Integer element = (Integer) stack.peek();
System.out.println("Element on stack top: " + element);
}
static void stack_search(Stack<Integer> stack, int element)
{
Integer pos = (Integer) stack.search(element);
if(pos == -1)
System.out.println("Element not found");
else
System.out.println("Element is found at position: " + pos);
}
public static void main (String[] args)
{
Stack<Integer> stack = new Stack<Integer>();
stack_push(stack);
stack_pop(stack);
stack_push(stack);
stack_peek(stack);
stack_search(stack, 2);
stack_search(stack, 6);
}
}
Example 4: stack class in java
import java.util.Stack;
class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();
animals.push("Dog");
animals.push("Horse");
animals.pop();
animals.peek();
}
}
Example 5: stack implementation in c
#include <stdio.h>
int MAXSIZE = 8;
int stack[8];
int top = -1;
int isempty() {
if(top == -1)
return 1;
else
return 0;
}
int isfull() {
if(top == MAXSIZE)
return 1;
else
return 0;
}
int peek() {
return stack[top];
}
int pop() {
int data;
if(!isempty()) {
data = stack[top];
top = top - 1;
return data;
} else {
printf("Could not retrieve data, Stack is empty.\n");
}
}
int push(int data) {
if(!isfull()) {
top = top + 1;
stack[top] = data;
} else {
printf("Could not insert data, Stack is full.\n");
}
}
int main() {
push(3);
push(5);
push(9);
push(1);
push(12);
push(15);
printf("Element at top of the stack: %d\n" ,peek());
printf("Elements: \n");
while(!isempty()) {
int data = pop();
printf("%d\n",data);
}
printf("Stack full: %s\n" , isfull()?"true":"false");
printf("Stack empty: %s\n" , isempty()?"true":"false");
return 0;
}
Example 6: stack implementation
typedef struct Nodo{
Elem val;
struct Nodo *next;
} *Stack;
Stack Empty(){return NULL;}
bool IsEmpty(Stack a){return a==NULL;}
Elem Top(Stack a){return a->val;}
Stack Pop(Stack l){return l->next;}
Stack Push(Elem x,Stack res){
Stack nuevo=(Stack)malloc(sizeof(struct Nodo));
nuevo->val=x;
nuevo->next=res;
return nuevo;
}