Professional Documents
Culture Documents
Ex.No.7
Implementation of Stack using Linked List
10-10-2022
AIM: To write and execute JAVA program to perform Stack using Singly Linked List.
Pseudocode:
push()
1. Intialize variable data
2. create *newnode of type struct node
3.allocate memory to newnode
4.if newnode=NULL
5. print(“Unable to allocate memory”)
6.else print(“Enter value”)
7. if top=NULL
8. newnode->data=data;
9. newnode->next=NULL;
10. top=newnode;
11. else
12. newnode->data=data
13. newnode->next=top
14. top=newnode;
pop()
1.create *temp of type struct node
2.if top=NULL
3. print (“Underflow”)
4.else temp<-top
5. top=temp->next;
6. print(“data to be deleted”,temp->data)
7. free(temp);
display()
1.struct node *temp;
2. temp<-top;
3.if top=NULL
4. print(“stack is empty”)
5.else
6. while(temp!=NULL)
7. print(“stack elements”)
8. temp=temp->next
Explanation:
push()
We are going to push/insert elements into stack
We have created a newnode pointer and allocated memory to it.
In line 4 we are checking if newnode=NULL if yes then it will print unable to
allocate memory ,if false else part will execute.
From line 6 we are taking the element value from the user and checking if
top=NULL , that means if there are no element inside the stack , if yes if will assign
newnode->data=data
Newnode->next=NULL
Top=newnode ,now our first element is top
In line 11 we are checking if there is already element in stack do newnode-
>data=data
Newnode->next=top and make top=newnode;
These will add the second element at the beginning and top will now point to this
element.
pop()
In pop function we delete the element that is at the top
We are creating a temp pointer that is pointing at top
If top=NULL that means there are no elements in the stack so it will print underflow
Else top=temp->next , now top will point to the next element
We are deleting the element at the beginning by deallocating its memory
free(temp)
display()
We are taking a new pointer temp
Assigning temp=top
If top =NULL , it will print stack is empty
Otherwise, it will print stack elements by checking while(temp!=NULL)
Print temp->data
Temp=temp->next , this loop is going to traverse all the nodes and print their data.
Example:
Program Code:
import java.util.Scanner;
}
class node
{
int data;
node next;
node(int data)
{
this.data=data;
this.next=null;
}
}
Output Screenshots:
RESULT: Thus, the programs for the given problem statements has been executed and
the results are verified successfully.