#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct Node
{
int val;
struct Node* next;
}Node;
typedef struct Stack
{
Node* head;
}Stack;
Node* initNode(int val)
{
Node* n = (Node*)malloc(sizeof(Node));
n->val = val;
n->next = NULL;
return n;
}
void freeNode(Node* n)
{
if (n) free(n);
return;
}
Stack* initStack()
{
Stack* s = (Stack*)malloc(sizeof(Stack));
s->head = NULL;
return s;
}
void freeStack(Stack* s)
{
if (!s) return;
Node* p = s->head, * k;
while (p)
{
k = p;
p = p->next;
freeNode(k);
}
free(s);
return;
}
bool push(Stack* s, int val)
{
if (!s) return 0;
Node* n = initNode(val);
n->next = s->head;
s->head = n;
return true;
}
bool isEmpty(Stack* s)
{
return !(s && s->head);
}
int pop(Stack* s)
{
Node* k = s->head;
int t = k->val;
s->head = k->next;
freeNode(k);
return t;
}
void showStack(Stack* s)
{
if (!s) return;
printf("Stack:[");
Node* p = s->head;
while (p)
{
printf("%d->", p->val);
p = p->next;
}
printf("NULL]\n");
}
int main()
{
srand(time(0));
Stack* s = initStack();
int cnt = 20;
while (cnt--)
{
int val = rand() % 100;
int op = rand() % 4;
switch (op)
{
case 0:
case 1:
case 2:
printf("push %d,res=%s\n", val, push(s, val) ? "SUS" : "ERR");
break;
case 3:
isEmpty(s) ? printf("pop nothing!\n") : printf("pop %d \n", pop(s));
}
showStack(s);
}
return 0;
}
4.数据结构之用链表实现栈
最新推荐文章于 2023-07-11 08:21:31 发布