Created
March 31, 2020 06:04
-
-
Save so77id/f73ef14763078780978f273544323bab to your computer and use it in GitHub Desktop.
Example of stacks implemented over linked list in java
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
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()); | |
} | |
} | |
} |
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
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; } | |
} |
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
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