Skip to content

Commit 27f02f6

Browse files
committed
c: queue using stack
Signed-off-by: Ayush Dubey <[email protected]>
1 parent a389fea commit 27f02f6

File tree

1 file changed

+120
-0
lines changed

1 file changed

+120
-0
lines changed

c/queueUsingStack.c

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
/* C Program to implement a queue using two stacks */
2+
#include <stdio.h>
3+
#include <stdlib.h>
4+
5+
/* structure of a stack node */
6+
struct sNode
7+
{
8+
int data;
9+
struct sNode *next;
10+
};
11+
12+
/* Function to push an item to stack*/
13+
void push(struct sNode **top_ref, int new_data);
14+
15+
/* Function to pop an item from stack*/
16+
int pop(struct sNode **top_ref);
17+
18+
/* structure of queue having two stacks */
19+
struct queue
20+
{
21+
struct sNode *stack1;
22+
struct sNode *stack2;
23+
};
24+
25+
/* Function to enqueue an item to queue */
26+
void enQueue(struct queue *q, int x)
27+
{
28+
push(&q->stack1, x);
29+
}
30+
31+
/* Function to deQueue an item from queue */
32+
int deQueue(struct queue *q)
33+
{
34+
int x;
35+
36+
/* If both stacks are empty then error */
37+
if (q->stack1 == NULL && q->stack2 == NULL)
38+
{
39+
printf("Q is empty");
40+
getchar();
41+
exit(0);
42+
}
43+
44+
/* Move elements from stack1 to stack 2 only if
45+
stack2 is empty */
46+
if (q->stack2 == NULL)
47+
{
48+
while (q->stack1 != NULL)
49+
{
50+
x = pop(&q->stack1);
51+
push(&q->stack2, x);
52+
}
53+
}
54+
55+
x = pop(&q->stack2);
56+
return x;
57+
}
58+
59+
/* Function to push an item to stack*/
60+
void push(struct sNode **top_ref, int new_data)
61+
{
62+
/* allocate node */
63+
struct sNode *new_node = (struct sNode *)malloc(sizeof(struct sNode));
64+
if (new_node == NULL)
65+
{
66+
printf("Stack overflow \n");
67+
getchar();
68+
exit(0);
69+
}
70+
71+
/* put in the data */
72+
new_node->data = new_data;
73+
74+
/* link the old list off the new node */
75+
new_node->next = (*top_ref);
76+
77+
/* move the head to point to the new node */
78+
(*top_ref) = new_node;
79+
}
80+
81+
/* Function to pop an item from stack*/
82+
int pop(struct sNode **top_ref)
83+
{
84+
int res;
85+
struct sNode *top;
86+
87+
/*If stack is empty then error */
88+
if (*top_ref == NULL)
89+
{
90+
printf("Stack underflow \n");
91+
getchar();
92+
exit(0);
93+
}
94+
else
95+
{
96+
top = *top_ref;
97+
res = top->data;
98+
*top_ref = top->next;
99+
free(top);
100+
return res;
101+
}
102+
}
103+
104+
int main()
105+
{
106+
/* Create a queue with items 1 2 3*/
107+
struct queue *q = (struct queue *)malloc(sizeof(struct queue));
108+
q->stack1 = NULL;
109+
q->stack2 = NULL;
110+
enQueue(q, 1);
111+
enQueue(q, 2);
112+
enQueue(q, 3);
113+
114+
/* Dequeue items */
115+
printf("%d ", deQueue(q));
116+
printf("%d ", deQueue(q));
117+
printf("%d ", deQueue(q));
118+
119+
return 0;
120+
}

0 commit comments

Comments
 (0)