Created
April 27, 2019 22:16
-
-
Save boki1/e06e641539d50af77b04a64c8cebb83d to your computer and use it in GitHub Desktop.
Dynamic stack implementation - School HW
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
struct node { | |
int data; | |
struct node *next; | |
}; | |
struct stack { | |
struct node *head; | |
int size; | |
}; | |
void init(struct stack *structstack) { | |
structstack->head = 0; | |
structstack->size = 0; | |
} | |
void push(struct stack *structstack, int value) { | |
struct node *_new = malloc(sizeof *_new); | |
_new->data = value; | |
_new->next = structstack->head; | |
structstack->head = _new; | |
structstack->size++; | |
} | |
int pop(struct stack *structstack, int *el) { | |
if (structstack->size <= 0) | |
return 0; | |
*el = structstack->head->data; | |
struct node *topop = structstack->head; | |
structstack->head = structstack->head->next; | |
free(topop); | |
structstack->size--; | |
return 1; | |
} | |
void show_stack(struct stack *structstack) { | |
struct node *n = structstack->head; | |
while (n) { | |
printf("%d ", n->data); | |
n = n->next; | |
} | |
} | |
int main(int argc, char *argv[]) { | |
struct stack _stack; | |
init(&_stack); | |
for (int i = 1; i < argc; ++i) { | |
push(&_stack, atoi(argv[i])); | |
printf("Pushed %d to the stack.\n", atoi(argv[i])); | |
} | |
int el; | |
for (int i = 0; i < argc; ++i) { | |
if (pop(&_stack, &el)) | |
printf("Popped %d from stack.\n", el); | |
else | |
printf("Stack empty.\n"); | |
} | |
show_stack(&_stack); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment