-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathquestion1.c
138 lines (119 loc) · 2.15 KB
/
question1.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/*
Implement a stack using arrays & linked-list
METHOD1: Using array
For pushing:
Time complexity:O(1)
For popping:
Time complexity:O(1)
METHOD2: Using linked list
For pushing:
Time complexity:O(1)
For popping:
Time complexity:O(1)
*/
//METHOD1:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
void push(int arr[],int elm, int *top){
if(*top == MAX-1){
printf("overflow\n");
return;
}
arr[++*top] = elm;
printf("VAL %d\n", *top);
return;
}
int pop(int arr[], int *top){
int temp;
if(*top == -1){
printf("underflow\n");
return -1;
}
temp = arr[(*top)--];
printf("VAL %d\n", *top);
return temp;
}
int main(){
int arr[MAX];
int top = -1;
int step, elm;
while(1){
printf("1. PUSH element\n");
printf("2. POP element\n");
printf("3.EXIT \n");
scanf("%d",&step);
switch(step){
case 1: printf("Enter the number to be pushed\n");
scanf("%d",&elm);
push(arr,elm, &top);
break;
case 2: elm = pop(arr, &top);
if(elm == -1){
printf("Already empty\n");
}else{
printf("%d was popped\n", elm);
}
break;
case 3: exit(1);
break;
}
}
return 0;
}
//==================================================================================
//METHOD2
#include <stdio.h>
#include <stdlib.h>
struct node *head = NULL;
struct node{
int data;
struct node *next;
};
void push(int data){
struct node *newnode = (struct node *)malloc(sizeof(struct node));
if(newnode == NULL){
printf("heap memory is full\n");
return;
}
newnode->data = data;
newnode->next = head;
head = newnode;
}
int pop(){
int data;
if(head == NULL){
return -1;
}
struct node *temp;
temp = head;
data = temp->data;
head = head->next;
free(temp);
return data;
}
int main(){
int step,elm;
while(1){
printf("1. PUSH element\n");
printf("2. POP element\n");
printf("3.EXIT \n");
scanf("%d",&step);
switch(step){
case 1: printf("Enter the number to be pushed\n");
scanf("%d",&elm);
push(elm);
break;
case 2: elm = pop();
if(elm == -1){
printf("Already empty\n");
}else{
printf("%d was popped\n", elm);
}
break;
case 3: exit(1);
break;
}
}
return 0;
}