-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack1.c
104 lines (96 loc) · 1.77 KB
/
stack1.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
96
97
98
99
100
101
102
103
104
//stack using linked list.
#include <stdio.h>
#include <stdlib.h>
struct node* create_a_stack(void);
void push(int,struct node*);
void print(struct node*);
void pop(struct node*);
struct node
{
int data;
struct node *next;
};
void main()
{
int c,n;
struct node *head;
printf("creating stack......\n");
head = create_a_stack();
printf("Stack created!\n");
do
{
printf("\t\t\t\tMAIN MENU\n");
printf("1.Push into stack\n");
printf("2.Pop out to stack\n");
printf("3.Display all elements of stack\n");
printf("4.Exit\n");
printf("Enter your choice....!\n");
scanf("%d",&c);
switch(c)
{
case 1: printf("Enter the number to be pushed into stack\n");
scanf("%d",&n);
push(n,head);
print(head);
break;
case 2: printf("Popping out an element from stack....\n");
pop(head);
print(head);
break;
case 3: print(head);
break;
case 4: return;
break;
}
}
while(c != 4);
}
struct node* create_a_stack()
{
struct node *ptr;
ptr = (struct node*)malloc(sizeof(struct node));
ptr->data = 0;
ptr->next = NULL;
return ptr;
}
void push(int n,struct node *ptr)
{
struct node *new_ptr;
ptr->data = ptr->data + 1;
new_ptr = (struct node*)malloc(sizeof(struct node));
new_ptr->data = n;
new_ptr->next = ptr->next;
ptr->next = new_ptr;
}
void print(struct node *ptr)
{
struct node *temp;
temp = ptr;
if(temp->next == NULL)
{
printf("Stack is empty !\n");
return;
}
printf("Loading stack....\n");
while(temp->next != NULL)
{
temp = temp->next;
printf("%d\n",temp->data);
}
}
void pop(struct node *ptr)
{
struct node *temp;
if(ptr->next == NULL)
{
printf("Error : Can not pop stack is empty...!\n");
return;
}
else
{
ptr->data = ptr->data - 1;
temp = ptr->next;
ptr->next = (ptr->next)->next;
free(temp);
}
}