-
Notifications
You must be signed in to change notification settings - Fork 1
/
sortstack.c
95 lines (95 loc) · 1.85 KB
/
sortstack.c
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
#include<stdio.h>
struct stack
{
int info;
struct stack *next;
};
//Function to initialize stack:
void initializeStack(struct stack **start)
{
*start = NULL;
}
//Function to check stack is empty:
int isEmpty(struct stack *start)
{
if (start == NULL)
return 1;
return 0;
}
//Function to push an item into stack
void push(struct stack **start, int a)
{
struct stack *p = (struct stack *)malloc(sizeof(*p));
if (p == NULL)
{
printf(stderr, "Memory allocation failed.\n");
return;
}
p->info = a;
p->next = *start;
*start = p;
}
//Function to remove an item from stack
int pop(struct stack **start)
{
int a;
struct stack *temp;
a = (*start)->info;
temp = *start;
(*start) = (*start)->next;
free(temp);
return a;
}
// Function to find top item
int top(struct stack *start)
{
return (start->info);
}
void printingStack(struct stack *start)
{
while (start)
{
printf("%d ", start->info);
start = start->next;
}
printf("\n");
}
// Recursive function to insert an item a in sorted way
void sortedInsert(struct stack **start, int a)
{
if (isEmpty(*start) || a > top(*start))
{
push(start, a);
return;
}
int temp = pop(start);
sortedInsert(start, a);
push(start, temp);
}
// Function to sort stack
void sortStack(struct stack **start)
{
if (!isEmpty(*start))
{
int a = pop(start);
sortStack(start);
sortedInsert(start, x);
}
}
int main(void)
{
struct stack *top;
initializeStack(&top);
push(&top, 20);
push(&top, -5);
push(&top, 19);
push(&top, 15);
push(&top, -3);
printf("Stack elements before sorting:\n");
printingStack(top);
sortStack(&top);
printf("\n\n");
printf("Stack elements after sorting:\n");
printingStack(top);
return 0;
}