Last active
April 6, 2022 06:45
-
-
Save alimranahmed/d812e1b5e3318b0d0642 to your computer and use it in GitHub Desktop.
Stack - Data Structure using Java(Without using library)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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