Sunday, June 14, 2020

Linked List Implementation of a Stack


Since by now you know Stack can be implemented in various ways -
Linked List implementation or Array implementation...

Its all about achieving Stack behavior and your constraint adjustment as per your needs, you can go either way (use Arrays or Linked List)-  here is one linked list implementation (Remember- you need to create your own linked list and do not use Java utility classes for such implementation), here is the code to help you understand:

************************************************
package Stack;

import java.util.Scanner;


// Stack Class
public class LinkedListImplementation {
public int size;
private Node node = null ;

LinkedListImplementation(){
new Node() ;
}

public boolean isEmpty() {
return node==null;
}

public int size() {
int size = 0;
Node temp = node;
while(temp !=null) {
temp = temp.next ;
size++;
}
return size;
}

public void push(String item) {
Node head = node;

node = new Node() ;
node.item = item;
node.next = head ;

}

public String pop() {
String item = node.getItem() ;
node = node.getNext() ;
return item;
}

public static void main(String args[]) {
Scanner sc = new Scanner(System.in) ;

LinkedListImplementation lstack = new LinkedListImplementation() ;
lstack.push("A");
lstack.push("B");
lstack.push("C");
lstack.push("D");

lstack.display();
System.out.println("");
System.out.println(lstack.size()) ;
lstack.pop();
lstack.display();

}

public void display() {
if(node == null)
return;
else {
Node temp = node;
while(temp!=null) {
System.out.print(temp.item+" -> ");
temp= temp.next;
}
}

}

}

****************************************************

/* Node Class  */

package Stack;

public class Node {

String item;
Node next ;

public Node(){
this.next = null;
this.item = null;
}

public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}

public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}


}

*************************************
This is very simple and easy implementation of Stack which provides all basic push, pop features..more features can be added as per needs.  


No comments:

Post a Comment