Skip to content

Instantly share code, notes, and snippets.

@so77id
Created March 31, 2020 06:04
Show Gist options
  • Save so77id/f73ef14763078780978f273544323bab to your computer and use it in GitHub Desktop.
Save so77id/f73ef14763078780978f273544323bab to your computer and use it in GitHub Desktop.
Example of stacks implemented over linked list in java
import java.util.Scanner; // Import the Scanner class
public class Main {
public static void main(String[] args){
int n, buff;
Node tmp;
Scanner scanner = new Scanner(System.in); // Create a Scanner object
Stack myStack = new Stack();
n = scanner.nextInt();
for(int i=0; i < n; i++){
buff = scanner.nextInt();
myStack.push(buff);
}
while(!myStack.empty()){
tmp = myStack.top();
myStack.pop();
System.out.println(tmp.getValue());
}
}
}
class Node {
private int value;
private Node next;
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
public Node(int value) {
this.value = value;
this.next = null;
}
public int getValue() { return (this.value); }
public void setValue(int value) { this.value = value; }
public Node getNext() { return (this.next); }
public void setNext(Node next) { this.next = next; }
}
class Stack {
private Node head;
public Stack() {
this.head = null;
}
public void push(int value) {
Node n_node = new Node(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 Node top(){
Node tmp = this.head;
return tmp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment