#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct Node {
int data;
struct Node* next;
}Node;
typedef struct Stack {
Node* top;
int length;
}Stack;
Node* getNewNode(int);
Stack* init_stack();
void clear(Stack*);
int empty(Stack*);
int push(Stack*, int);
int pop(Stack*);
void output(Stack*);
int top(Stack*);
Node* getNewNode(int val) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = val;
node->next = NULL;
return node;
}
Stack* init_stack() {
Stack* s = (Stack*)malloc(sizeof(Stack));
s->length = 0;
s->top = NULL;
return s;
}
void clear(Stack* s) {
if (s == NULL) return;
Node* p = s->top,*q;
while (p!= NULL) {
q = p->next;
free(p);
p = q;
}
free(s);
return;
}
int empty(Stack *s) {
return s->top == NULL;
}
int top(Stack* s) {
return s->top->data;
}
int push(Stack* s, int val) {
if (s == NULL) return 0;
Node* p = getNewNode(val);
p->next = s->top;
s->top = p;
s->length += 1;
return 1;
}
int pop(Stack* s) {
if (s == NULL) return 0;
if (empty(s)) return 0;
Node* p = s->top;
s->top = p->next;
free(p);
s->length -= 1;
return 1;
}
void output(Stack* s) {
if (s == NULL) return ;
printf("Stack[%d]: ",s->length);
for (Node* p = s->top; p; p = p->next) {
p != s->top && printf(" ");
printf("%d", p->data);
}
printf("\n");
return;
}
int main() {
srand(time(0));
#define MAX_OP 20
Stack* s = init_stack();
for (int i = 0; i < MAX_OP; i++) {
int op = rand() % 4;
int val = rand() % 100;
switch (op) {
case 0:
case 1:
case 2: {
printf("push %d to the Stack = %d\n", val, push(s, val));
}break;
case 3: {
if (!empty(s)) {
printf("pop %d from the Stack = ", top(s));
printf("%d\n", pop(s));
}
}break;
}
output(s);
printf("\n");
}
#undef MAX_OP
free(s);
return 0;
}