Untitled
unknown
plain_text
2 years ago
1.1 kB
9
Indexable
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *top = NULL;
void push(int value) {
struct node *new_node = (struct node*) malloc(sizeof(struct node));
new_node->data = value;
new_node->next = top;
top = new_node;
}
void pop() {
if (top == NULL) {
printf("Stack is empty.\n");
return;
}
struct node *temp = top;
top = top->next;
free(temp);
}
int peek() {
if (top == NULL) {
printf("Stack is empty.\n");
return -1;
}
return top->data;
}
int main() {
int input, value;
while (1) {
scanf("%d", &input);
if (input == -1) break;
switch(input) {
case 1:
scanf("%d", &value);
push(value);
break;
case 2:
pop();
break;
case 3:
printf("%d\n", peek());
break;
default:
printf("Invalid input.\n");
}
}
return 0;
}Editor is loading...