Skip to content

Instantly share code, notes, and snippets.

@skharel
Created April 23, 2014 23:56
Show Gist options
  • Save skharel/11236623 to your computer and use it in GitHub Desktop.
Save skharel/11236623 to your computer and use it in GitHub Desktop.
/*
*
* This code is written for Stacks tutorial
* The comment won't make sense unless you read the slide that goes with it
*
* Go to Vumari.com to find the slide
*
*/
public class LinkedListStacks {
//node
private static class Node {
int data;
Node previous;
Node(int data){
this.data = data;
previous = null; // newly create node points to nothing
}
}
private Node pointer;
private int size = 0;
public void push(int aData){
Node aNewNode = new Node(aData);
if(pointer == null){//first node
pointer = aNewNode;
}else{
aNewNode.previous = pointer; //talk to the old guy
pointer = aNewNode; //pointer goes to the top
}
size++;
}
public int pop(){
if(pointer == null){
throw new NullPointerException("There is nothing to pop from the stack.");
}
int temp = pointer.data;
pointer = pointer.previous;//go to the previous guy
size--;
return temp;
}
public int getSize(){
return size;
}
public boolean isEmpty(){
return pointer == null;
}
@Override
public String toString() {
Node printer = pointer; //start from top
StringBuilder allData = new StringBuilder();
while(printer != null){
allData.append(printer.data + ", ");
printer = printer.previous;
}
return allData.toString().replaceAll(", $", "");//remove , followed by space in the end for nice printing
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment