Skip to content

Instantly share code, notes, and snippets.

@yssharma
Created November 3, 2012 13:58
Show Gist options
  • Save yssharma/4007451 to your computer and use it in GitHub Desktop.
Save yssharma/4007451 to your computer and use it in GitHub Desktop.
A basic java implementation of Stack data structure. (Confused Coders)
class Item {
intdata;
Item next;
public Item(int data) {
this.data = data;
}
}
public class Stack {
private Item top;
public void push(int data) {
if (null == top) {
top = new Item(data);
} else {
Item item = new Item(data);
item.next = top;
top = item;
}
}
public int pop() {
int data = top.data;
top = top.next;
return data;
}
public void printStack() {
Item tmp = top;
if (top == null) {
System.out.print("Stack is empty !!");
}
System.out.println();
while (tmp != null) {
System.out.print(" > " + tmp.data);
tmp = tmp.next;
}
}
public static void main(String[] args) {
Stack stack = new Stack();
stack.printStack();
stack.push(5);
stack.push(14);
stack.push(3);
stack.push(23);
stack.printStack();
System.out.print("\npoped: " + stack.pop());
System.out.print("\npoped: " + stack.pop());
stack.printStack();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment