Skip to content

Instantly share code, notes, and snippets.

@so77id
Created September 4, 2020 19:53
Show Gist options
  • Save so77id/4fb531d66d8b74e7c24ec650edd8b766 to your computer and use it in GitHub Desktop.
Save so77id/4fb531d66d8b74e7c24ec650edd8b766 to your computer and use it in GitHub Desktop.
Stack in Java Generic
import java.util.Scanner; // Import the Scanner class
public class Main {
public static void main(String[] args){
int n;
int buff;
Scanner scanner = new Scanner(System.in); // Create a Scanner object
Stack<Integer> myStack = new Stack<Integer>();
System.out.println("Ingrese la cantidad de datos que va a adicionar al stack");
n = scanner.nextInt();
for(int i=0; i < n; i++){
buff = scanner.nextInt();
myStack.push(buff);
}
while(!myStack.empty()){
buff = myStack.top();
myStack.pop();
System.out.println(buff);
}
// int n;
// String buff;
// Scanner scanner = new Scanner(System.in); // Create a Scanner object
//
// Stack<String> myStack = new Stack<String>();
// System.out.println("Ingrese la cantidad de datos que va a adicionar al stack");
// n = scanner.nextInt();
//
// for(int i=0; i < n; i++){
// buff = scanner.next();
// myStack.push(buff);
// }
//
// while(!myStack.empty()){
// buff = myStack.top();
// myStack.pop();
// System.out.println(buff);
// }
}
}
class Node<T extends Comparable<T>> {
private T value;
private Node next;
public Node(T value, Node next) {
this.value = value;
this.next = next;
}
public Node(T value) {
this.value = value;
this.next = null;
}
public Node() {
this.value = null;
this.next = null;
}
public T getValue() { return this.value; }
public Node getNext() { return this.next; }
public void setValue(T value) { this.value = value; }
public void setNext(Node next) { this.next = next; }
}
class Stack<T extends Comparable<T>> {
private Node<T> head;
public Stack() {
this.head = null;
}
public void push(T value) {
Node<T> n_node = new Node<T>(value, this.head);
this.head = n_node;
}
public void pop() {
if (this.head != null) {
this.head = this.head.getNext();
}
}
public boolean empty(){
if (this.head == null) return true;
else return false;
}
public T top(){
return this.head.getValue();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment