Also Read
Stack Implementation Using Linked List
A Stack is a conceptual data structure that contains a collection of homogenous elements. Stack follows the mechanism of FILO (First In Last Out) and LIFO (Last In First Out), which means that whichever element is inserted at the first number in the stack will be removed at the end and the element inserted at the end will be removed first.In today's article we can do Stack Implementation Using Linked List . First we understand the 3 basic operations that are used in the stack.
Push: The push function inserts the data value into the stack.
Pop: The pop function returns the data value that is at the top of the stack and removes it from the stack.
Peek: The pop function returns the data value that is at the top of the stack.
Linked List Implementation Of Stack
import java.util.Scanner;
class Node
{
char value;
Node next;
}
public class StackUsingLinkedList
{
Node firstNode = null;
public void push(char v) {
Node n = new Node();
n.value=v;
if(firstNode==null) {
firstNode=n;
}
else {
n.next=firstNode;
firstNode=n;
}
}
public char pop() {
if(firstNode==null) {
return '$';
}else {
char v = firstNode.value;
firstNode=firstNode.next;
return v;
}
}
public char peek() {
if(firstNode==null)
return '$';
else {
char v = firstNode.value;
return v;
}
}
public void display() {
Node temp = firstNode;
while(temp!=null) {
System.out.print(temp.value+" ");
temp=temp.next;
}
System.out.println();
}
//main method
public static void main(String[] args) {
StackUsingLinkedList obj = new StackUsingLinkedList();
Scanner scanner = new Scanner(System.in);
int choice;
while(true) {
System.out.print("\n1. Push value in Stack\n2. Pop value form Stack\n3. Display all values in Stack\n4. Exit\n");
choice = scanner.nextInt();
switch (choice) {
case 1: {
System.out.print("\nEnter value : ");
char v = scanner.next().charAt(0);
obj.push(v);
continue;
}
case 2:{
System.out.println(obj.pop());
continue;
}
case 3:{
obj.display();
continue;
}
case 4:
break;
}
if(choice==4)
break;
}
System.out.println("Thanks...");
}
}
Output
I am also giving you the download link of the entire file here, if you need it, you can download it.
if any issue comes, you can comment us or you can watch a video on this topic on our YouTube Channel.
You Might Like:
- Explain Different types of Software Requirements.
- Explain Agile Development in detail.
- Explain the steps in Requirements Engineering Process.
- Define Software testing and explain its types in detail.
- Implementation of Min Heap in Java.
- Most Popular Programming Languages in 2022.
- What is System Installation & explain its types in detail.
- Explain the types of System Maintenance.
0 Comments