Created
September 29, 2020 04:12
-
-
Save malvat/880f457adbf60684e71151944ead9911 to your computer and use it in GitHub Desktop.
A stack implementation using linked list in java
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
/** | |
* a stack implementation using linked list | |
* @author Anim Malvat | |
*/ | |
public class LinkedStack { | |
/** | |
* top pointer for stack | |
*/ | |
private Node top = null; | |
/** | |
* size of the stack | |
*/ | |
private int size = 0; | |
/** | |
* helper class that contains the information of the node | |
*/ | |
public class Node { | |
/** | |
* integer data to be stored | |
*/ | |
private int data; | |
/** | |
* reference to the next element | |
*/ | |
private Node next; | |
/** | |
* constructor of the node with value to be stored | |
*/ | |
public Node(int data) { | |
this.data = data; | |
this.next = null; | |
} | |
/** | |
* getter for the data | |
* @return the data | |
*/ | |
public int getData() { | |
return this.data; | |
} | |
/** | |
* getter for the next reference | |
* @return node | |
*/ | |
public Node getNext() { | |
return this.next; | |
} | |
/** | |
* sets the data of the node | |
* @param data integer data to be stored | |
*/ | |
public void setData(int data) { | |
this.data = data; | |
} | |
/** | |
* sets the next reference of the node | |
* @param next Node reference of the next node | |
*/ | |
public void setNext(Node next) { | |
this.next = next; | |
} | |
} | |
/** | |
* adds the element on the top pointer | |
* @param data | |
*/ | |
public void push(int data) { | |
this.size += 1; | |
if (this.top == null) { | |
this.top = new Node(data); | |
} else { | |
Node second = this.top; | |
this.top = new Node(data); | |
this.top.setNext(second); | |
} | |
} | |
/** | |
* removes the top most element and returns | |
* @return | |
*/ | |
public int pop() { | |
this.size -= 1; | |
int value = this.top.getData(); | |
this.top = this.top.getNext(); | |
return value; | |
} | |
/** | |
* displays the stack | |
*/ | |
public void display() { | |
Node iterator = this.top; | |
while (iterator != null) { | |
System.out.print(iterator.getData() + " "); | |
iterator = iterator.getNext(); | |
} | |
System.out.println(); | |
} | |
/** | |
* returns the size of the stack | |
* @return | |
*/ | |
public int getSize() { | |
return size; | |
} | |
public static void main(String[] args) { | |
LinkedStack stack = new LinkedStack(); | |
stack.push(3); | |
stack.push(2); | |
stack.push(1); | |
stack.display(); | |
stack.pop(); | |
stack.display(); | |
System.out.println("this size of the stack is : " + stack.getSize()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment