C Program to implement STACK operations using Linked Lists

C Program to implement STACK operations using Linked Lists.
Source: Dr. G T Raju, Professor & Head, Dept. of CSE, RNSIT

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <stdlib.h>
typedef struct node
{
int data;
struct node *link;
}NODE;
 
void Push(int);
int  pop();
void Display();
NODE *top=NULL;   /* Global Declarations */
 
main()
{
/* Main Program */
int opn,elem;
do
{
clrscr();
printf("\n ### Linked List Implementation of STACK Operations ### \n\n");
printf("\n Press 1-Push, 2-Pop, 3-Display,4-Exit\n");
printf("\n Your option ? ");
scanf("%d",&opn);
switch(opn)
{
case 1:
printf("\n\nRead the Element tobe pushed ?");
scanf("%d",&elem);
Push(elem);
break;
case 2:
elem=Pop();
if(elem != -1)
printf(" Deleted Node(From Top)with the Data: %d\n",elem);
break;
case 3: printf("Linked List Implementation of Stack: Status:\n");
Display(); break;
case 4: printf("\n\n Terminating \n\n"); break;
default: printf("\n\nInvalid Option !!! Try Again !! \n\n");
break;
}
printf("\n\n\n\n  Press a Key to Continue . . . ");
getch();
}while(opn != 4);
}
 
void Push(int info)
{
NODE *temp;
temp=(NODE *)malloc(sizeof(NODE));
if( temp == NULL)
printf(" Out of Memory !! Overflow !!!");
else
{
temp->data=info;
temp->link=top;
top=temp;
printf(" Node has been inserted at Top(Front) Successfully !!");
}
}
 
int Pop()
{
int info;
NODE *t;
if( top ==  NULL) { printf(" Underflow!!!"); return -1; }
else
{
t=top;
info=top->data;
top=top->link;
t->link=NULL;
free(t);
return(info);
}
}
 
void Display()
{
NODE *t;
if( top == NULL) printf("Empty Stack\n");
else
{
t=top;
printf("Top->");
while(t)
{
printf("[%d]->",t->data);
t=t->link;
}
printf("Null\n");
}
}
Ansten Lobo

6 thoughts on “C Program to implement STACK operations using Linked Lists

  1. @vidhi: The implementation of Stack is given very clearly. It is like a single linked list with addition and deletion of nodes happening at the head.
    In case of QUEUE, the addition happens at the Tail and the insertion happens at the head.

    STACK:

    head
    []—->[]—->[]—->[]

    QUEUE:

    head tail
    []—->[]—->[]—->[]

  2. is there a overflow condition in stack , when it is implemented using linked list ?
    becoz while implementing stack using linked list , “n” no of nodes can b created ?

  3. stacks using single linked list is clear but it would be more better if stacks using single linked list to display the give integers in reverse & same order ,if mentioned .

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in