Skip to content

Instantly share code, notes, and snippets.

@alimranahmed
Last active April 6, 2022 06:45
Show Gist options
  • Save alimranahmed/d812e1b5e3318b0d0642 to your computer and use it in GitHub Desktop.
Save alimranahmed/d812e1b5e3318b0d0642 to your computer and use it in GitHub Desktop.
Stack - Data Structure using Java(Without using library)
/**
* A implementation of Stack using Java Generic Programming
* @author Al- Imran Ahmed
*/
public class Stack<T>{
//Top node of the stack
private Node top = null;
/**
* InnerClass to represent the data elements as in stack
*/
class Node{
T item;
Node next;
}
/**
* Remove the top element of the stack and return the value of that element
* @return T
* public T pop(){ return null; } ;stub
*/
public T pop(){
if(isEmpty()){
return null;
}
T item = top.item;
top = top.next;
return item;
}
/**
* Insert an element to the stack
* @param T s
* public void push(T s){ return null; } ;sbub
*/
public void push(T s){
Node oldtop = top;
top = new Node();
top.item = s;
top.next = oldtop;
}
/**
* Check whether the stack is empty or not
* @return boolean
* public boolean isEmpty(){ return false; } ;stub
*/
public boolean isEmpty(){
return top == null;
}
}
/**
* Client to Testing Queue.java
* @author Al- Imran Ahmed
* java Client < input.txt
*/
import java.util.Scanner;
public class StackClient{
//Client method
public static void main(String[] CHAND){
//Create an instance of stack
Stack<String> stack = new Stack<String>();
Scanner input = new Scanner(System.in);
String s;
System.out.println("Output: ");
while(input.hasNext()){
s = input.next();
if(s.equals("-")){
System.out.print(stack.pop()+" ");
}else{
stack.push(s);
}
}
System.out.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment