C LAB‎ > ‎(Sem2) Data Structures‎ > ‎

Qx12. WAP to implement Stacks using Linked Lists.

posted Feb 9, 2011, 9:55 AM by Neil Mathew   [ updated Feb 9, 2011, 9:57 AM ]
SOURCE CODE:

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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <stdio.h>
 
struct node
{
       int info;
       struct node * next;
}*top,*temp;
 
 
void PUSH(int item)
{
struct node *newnode;
newnode = (struct node *) malloc ( sizeof(struct node) );
 
if(newnode==NULL)
printf(" NO SPACE LEFT ");
else
{
    
newnode->info=item;
 
if( top == NULL )
{ 
newnode->next=NULL;
top=newnode;
}
else 
{ 
newnode->next=top;
top=newnode;
}
 
} //end of outer else
}// end of func
 
 
void POP()
{
if(top==NULL)
printf("\n Stack Empty. \n");
else
{
printf("\n Node with Info=%d is deleted. \n", top->info);
temp=top;
top=top->next;
free(temp);
}
}
 
void DISPLAY()
{
if(top==NULL)
printf("\n Stack is empty. ");
else
{
temp=top;
 
printf("\n");
while(temp!=NULL)
{
printf("\n |%d| ", temp->info);
temp=temp->next;
}
printf("\n");
}//end of else
}     
 
 
int main()
{
    int item,ch=1;
    top=NULL;
 
    
   while(ch!=4)
    {
    printf("\n MENU: ");
    printf("\n 1. Insert a node. ");
    printf("\n 2. Delete a node. ");
    printf("\n 3. Display Stack. ");
    printf("\n 4. EXIT \n Your Choice: ");
    scanf("%d",&ch);
    
    switch(ch)
    {
    case 1: //INSERT
        
    printf("\n ENTER ITEM: ");
    scanf("%d", &item);
    
    PUSH(item);
    break;
    
    case 2: //DELETE
    POP();
    break;
    
    case 3: //DISPLAY
    DISPLAY();
    break;
    
    case 4: 
    printf("\n Exiting.. ");
    break;
    
    default: printf(" INVALID CHOICE. ");
    
    }
    
    }; //end of while loop
    return 0;
    
}
 

OUTPUT:

MENU: 
 1. Insert a node. 
 2. Delete a node. 
 3. Display Stack. 
 4. EXIT 
 Your Choice: 1

 ENTER ITEM: 64

 MENU: 
 1. Insert a node. 
 2. Delete a node. 
 3. Display Stack. 
 4. EXIT 
 Your Choice: 1

 ENTER ITEM: 89

 MENU: 
 1. Insert a node. 
 2. Delete a node. 
 3. Display Stack. 
 4. EXIT 
 Your Choice: 1

 ENTER ITEM: 90

 MENU: 
 1. Insert a node. 
 2. Delete a node. 
 3. Display Stack. 
 4. EXIT 
 Your Choice: 3


 |90| 
 |89| 
 |64| 

 MENU: 
 1. Insert a node. 
 2. Delete a node. 
 3. Display Stack. 
 4. EXIT 
 Your Choice: 2

 Node with Info=90 is deleted. 

 MENU: 
 1. Insert a node. 
 2. Delete a node. 
 3. Display Stack. 
 4. EXIT 
 Your Choice: 2


 |89| 
 |64| 

 MENU: 
 1. Insert a node. 
 2. Delete a node. 
 3. Display Stack. 
 4. EXIT 
 Your Choice: 4

 Exiting.. 

Comments