#include <stdio.h>
#include <stdlib.h>
// 无头栈
typedef struct linkstack
{
int data;
struct linkstack* next;
}linkstack;
// 入栈
void pushStack(linkstack** top, int data)
{
linkstack* node = (linkstack*)malloc(sizeof(linkstack));
if (node == NULL)
{
perror("push malloc error\n");
return;
}
node->data = data;//存入数据
node->next =*top;//改变新节点指向
*top = node;//改变栈针指向,确保永远指向栈顶
}
// 判断栈空
int isFullStack(linkstack* top)
{
return top == NULL;
}
// 出栈
int popStack(linkstack** top)
{
if (isFullStack(*top))
{
printf("空栈!\n");
return -1;
}
// int temp;
linkstack* p = *top;
int temp = p->data;
(*top) = (*top)->next;
free(p);
p = NULL;
return temp;
}
// 栈数量
void stackLength(linkstack* top)
{
int temp = 0;
while (top)
{
top = top->next;
temp++;
}
printf("栈数量:%d\n", temp);
}
// 获取栈顶数据
void getTopData(linkstack* top)
{
printf("栈顶:%d\n", top->data);
}
// 清空栈
void noneStack(linkstack** top)
{
while (!isFullStack(*top))
{
popStack(top);
}
printf("已清空!\n");
}
// 遍历
void printStack(linkstack* top)
{
while (top)
{
printf("%d->", top->data);
top = top->next;
}
printf("NULL\n");
}
int main(int argc, char const *argv[])
{
linkstack* top = NULL;//创建空栈,
pushStack(&top, 1);
pushStack(&top, 2);
pushStack(&top, 3);
pushStack(&top, 4);
pushStack(&top, 5);
printStack(top);
stackLength(top);
printf("出栈:%d\n", popStack(&top));
printStack(top);
getTopData(top);
printf("出栈:%d\n", popStack(&top));
printStack(top);
getTopData(top);
noneStack(&top);
stackLength(top);
return 0;
}
无头链式栈操作集合
最新推荐文章于 2024-06-26 22:39:02 发布