Created
April 23, 2014 23:56
-
-
Save skharel/11236623 to your computer and use it in GitHub Desktop.
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
/* | |
* | |
* 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