初学栈Ⅱ

初学栈Ⅱ


这篇主要是讲关于栈的链式储存。

栈的链式储存

栈的链式储存结构,简称为栈链

其实栈链本质上就是链表嘛~

用C语言表示大概是这样的:

1
2
3
4
5
6
7
8
9
10
11
struct stacknode //节点
{
int data;
struct stacknode *next;
};
struct linkstack //栈链
{
struct stacknode *top;
int count;
};

栈链的结构示意

入栈操作

1
2
3
4
5
6
7
8
9
10
void push(struct linkstack *s,int num)
{
struct stacknode *t;
t = (struct stacknode*)malloc(sizeof(struct stacknode));
t->data = num;
t->next = s->top;
s->top = t;
s->count++;
return;
}

出栈操作

1
2
3
4
5
6
7
8
9
10
11
int pop(struct linkstack *s,int *e)
{
struct stacknode *t;
if(s->count == 0) return -1;
t = s->top;
*e = t->data;
s->top = t->next;
free(t);
s->count--;
return 0;
}

创建一个栈

务必记得执行s->count = 0这一操作!

1
2
3
4
5
6
7
8
9
10
11
void create_linkstack(struct linkstack *s,int n)
{
int num;
s->count = 0;
while(n--)
{
scanf("%d",&num);
push(s,num);
}
return;
}

遍历输出栈内的元素

1
2
3
4
5
6
7
8
void print(struct linkstack *s)
{
int e;
while(~pop(s,&e))
printf("%d ",e);
printf("\n");
return;
}