Skip to content

Instantly share code, notes, and snippets.

@z1nc0r3
Created August 27, 2022 12:13
Show Gist options
  • Save z1nc0r3/84e31bf8089c144a4d35b28b5a32854b to your computer and use it in GitHub Desktop.
Save z1nc0r3/84e31bf8089c144a4d35b28b5a32854b to your computer and use it in GitHub Desktop.
Stack using Linked List
class Node {
String data;
Node next;
Node(String data) {
this.data = data;
next = null;
}
}
class Stack {
private Node top = null;
private int counter = 0;
public void push(String value) {
Node newNode = new Node(value);
if (top == null) {
top = newNode;
} else {
newNode.next = top;
top = newNode;
}
counter++;
}
public void pop() {
if (!isEmpty()) {
System.out.println(top.data);
top = top.next;
} else {
System.out.println("stack underflow");
}
counter--;
}
public void peek() {
System.out.println(!isEmpty() ? top.data : "stack underflow");
}
public boolean isEmpty() {
return (top == null);
}
public void print() {
Node temp = top;
for (int i=0; i<counter; i++) {
System.out.print(top.data + ", ");
top = top.next;
}
top = temp;
}
}
public class LinkedStack {
public static void main(String[] args) {
Stack s = new Stack();
s.push("D1");
s.push("D2");
s.push("D3");
s.push("D4");
s.push("D5");
s.push("D6");
s.push("D7");
s.pop();
s.peek();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment