Skip to content

Instantly share code, notes, and snippets.

@LordRahl90
Last active November 1, 2018 11:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LordRahl90/6f835040f9d93f452e935b0b5fdf613a to your computer and use it in GitHub Desktop.
Save LordRahl90/6f835040f9d93f452e935b0b5fdf613a to your computer and use it in GitHub Desktop.
Implementation of stack with java. Hoping to push golang with this understanding soon.
public class Stack{
private Node head;
//I Prefer this to having to walk the length of the stack everytime.
private int length=0;
//In case there is a node to be initialized with this stack. hence this constructor.
public Stack(Node head){
this.head=head;
}
public Stack(){
this.head=null;
}
public void printStack(){
Node n = head;
while(n!=null){
System.out.println(n.data+"");
n=n.next;
}
}
public void push(int item){
Node newItem=new Node(item);
newItem.next=head;
head=newItem;
this.length++;
}
public Node pop(){
Node currentItem=head;
head=head.next;
this.length--;
return currentItem;
}
public Node top(){
return this.head;
}
public int getLength(){
return this.length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment