-
Notifications
You must be signed in to change notification settings - Fork 0
/
stackList.c
81 lines (73 loc) · 1.39 KB
/
stackList.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
#include <stdio.h>
#include <stdlib.h>
struct node //Struct to hold the elements
{
int element;
struct node * next;
};
struct node *tos = NULL;
struct node *p = NULL;
void push(int x) // Helper to add elements
{
struct node *ele, *temp;
ele = (struct node*)malloc(sizeof(struct node));
ele->element = x;
ele->next = NULL;
if (tos == NULL)
tos = ele;
else
{
temp = tos;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next = ele;
}
}
int pop()
{
struct node *temp, *secondLast;
temp = tos;
secondLast = tos;
while(temp->next != NULL)
{
secondLast = temp;
temp = temp->next;
}
if(temp == tos)
{
tos = NULL;
}
else
{
secondLast->next = NULL;
}
free(temp);
}
void traverse() // Function to print out the elements
{
struct node *t;
t = tos;
while (t!= NULL)
{
printf("%d\n", t->element);
t=t->next;
}
}
int main() //Driver function
{
int c, data,n=0;
printf("Enter the number of nodes:");
scanf("%d", &n);
for(c=1; c<=n; c++)
{
printf("Enter the data for stack pos %d: ", c);
scanf("%d", &data);
printf("\n");
push(data);
}
pop();
traverse();
return 0;
}