Stack implementation using linked list
Push operation:
1. create a new node with the given element.
2. Make the next of the new node to point to the top element.
3. Make top element to point to the new node.
Pop operation:
1. Store the data of top element.
2. Make top to point to top->next. (you need not free the memory here since java makes garbage collection for unused references)
Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class Node
{
int data;
Node next;
Node(int data){
this.data = data;
next = null;
}
}
class Stack
{
Node top = null;
public int pop(){
if (top == null){
System.out.println("stack is empty");
return 0;
}
int data = top.data;
top = top.next;
return data;
}
public void push(int element){
Node newNode = new Node(element);
newNode.next = top;
top = newNode;
return;
}
public static void main (String[] args){
Stack s = new Stack();
s.push(1);
s.push(3);
System.out.println(s.pop()+ " is popped from the stack");
s.push(5);
System.out.println(s.pop()+ " is popped from the stack");
}
}
Illustration:
1. create a new node with the given element.
2. Make the next of the new node to point to the top element.
3. Make top element to point to the new node.
Pop operation:
1. Store the data of top element.
2. Make top to point to top->next. (you need not free the memory here since java makes garbage collection for unused references)
Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class Node
{
int data;
Node next;
Node(int data){
this.data = data;
next = null;
}
}
class Stack
{
Node top = null;
public int pop(){
if (top == null){
System.out.println("stack is empty");
return 0;
}
int data = top.data;
top = top.next;
return data;
}
public void push(int element){
Node newNode = new Node(element);
newNode.next = top;
top = newNode;
return;
}
public static void main (String[] args){
Stack s = new Stack();
s.push(1);
s.push(3);
System.out.println(s.pop()+ " is popped from the stack");
s.push(5);
System.out.println(s.pop()+ " is popped from the stack");
}
}
Illustration:



Comments
Post a Comment