一、 定义
-
栈(stack)是限定仅在表的一端进行操作的数据结构。先进后出。
-
栈分为数组栈和链表栈。
数组栈使用数组进行功能的模拟,实现较为快速和便利。
链表栈使用链表的思路去设计,实现较为麻烦,但是其稳定不易出错;
- 在链表栈中又分为静态链表栈和动态链表栈。
静态链表栈给定栈的空间大小,不允许超过存储超过给定数据大小的元素
动态链表栈使用的是自动创建空间的方法进行创建,只要符合机器的硬件要求以及编译器的控制,其理论上是极大的。
二、栈的设计
栈的结构体包括了一个永远指向栈头的指针top和一个计数器count记录元素个数
(也可以设计成一个指针top和一个指针bottom分别指向栈头和栈尾)
判断栈何时为空:count的方法是当count为0时为空,top和bottom方法就是两者指向同一个空间时为栈为空
typedef struct node
{
int data;
struct node *next;
} Node;
//利用上面的结点创建栈,分为指向头结点的top指针和计数用的count
typedef struct stack
{
Node *top;
int count;
} Link_Stack;
三、基本操作
- 入栈(push)
Link_Stack *Push_stack(Link_Stack *p, int elem)
{
if (p == NULL)
return NULL;
Node *temp;
temp=(Node*)malloc(sizeof(Node));
//temp = new Node;
temp->data = elem;
temp->next = p->top;
p->top = temp;
p->count++;
return p;
}
- 出栈(pop)
在栈不为空的情况下(注意一定要进行判空操作),将栈顶的元素删除,同时top指针,next向下进行移动即可
ink_Stack *Pop_stack(Link_Stack *p)
{
Node *temp;
temp = p->top;
if (p->top == NULL)
{
printf("错误:栈为空");
return p;
}
else
{
p->top = p->top->next;
free(temp);
//delete temp;
p->count--;
return p;
}
}
- 遍历
1️⃣判空2️⃣temp = temp->next;
Node *temp;
temp = p->top;
if (p->top == NULL)
{
printf("栈为空");
}
while (temp != NULL)
{
printf("%d\t", temp->data);
temp = temp->next;
}