#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct Stack
{
int* data;
int top;
int size;
}Stack;
Stack* initStack(int n)
{
Stack* s = (Stack*)malloc(sizeof(Stack));
s->data = (int*)malloc(sizeof(int) * n);
s->top = -1;
s->size = n;
return s;
}
bool expand(Stack* s)
{
if (!s) return false;
int size = s->size;
int *p = NULL;
while (size)
{
p = (int*)realloc(s->data,sizeof(int) * (s->size + size));
if (p) break;
size >= 1;
}
if (!p) return false;
s->data = p;
s->size += size;
printf("expand success,new size is %d\n", s->size);
return true;
}
bool push(Stack* s, int val)
{
if (!s) return false;
if (s->top == s->size - 1)
{
if (!expand(s)) return false;
}
s->data[++s->top] = val;
return true;
}
bool isEmpty(Stack* s)
{
return !s || s->top == -1;
//return !(s && s->top != -1);
}
bool pop(Stack* s)
{
return s->data[s->top--];
}
void freeStack(Stack** s)
{
if (!(*s)) return;
free((*s)->data);
free((*s));
*s = NULL;
return;
}
void showStack(Stack* s)
{
if (isEmpty(s)) return;
printf("Stack:[");
int i;
for (i = 0; i <= s->top; i++)
{
i&& printf(",");
printf("%d", s->data[i]);
}
printf("]\n");
}
int main()
{
srand(time(0));
Stack* s = initStack(1);
int cnt = 20;
while (cnt--)
{
int val = rand() % 100;
int opt = rand() % 4;
switch (opt) {
case 0:
case 1:
case 2:
printf("push %d,res =%s\n",val,push(s, val)?"SUC":"ERR");
break;
case 3:
isEmpty(s) ? printf("pop nothing~\n") : printf("pop %d\n", pop(s));
break;
}
showStack(s);
}
freeStack(&s);
printf("%x\n", s);
return 0;
}
3.数据结构之栈
最新推荐文章于 2023-04-21 20:16:46 发布