链栈 c语言实现
程序员文章站
2022-05-26 19:40:45
...
下午有实现了链栈,而且知道了光标变大的解决方法,按inser键即可解决这个烦人的问题
完整代码
#include <stdio.h>
#include <stdlib.h>
typedef struct lineStack {
int data;
struct lineStack *next;
}linestack;
//入栈
linestack * push(linestack *stack, int i)
{
linestack *temp = (linestack*)malloc(sizeof(linestack));
temp->data = i;
temp->next = stack;
stack = temp;
return stack;
}
linestack * pop(linestack *stack)
{
if (stack)
{
linestack *temp = stack;
stack = stack->next;
printf("出栈元素%d", temp->data);
if (stack)
{
printf("栈顶元素%d\n", stack->data);
}
free(temp);
return stack;
}
else
{
printf("栈已经空了\n");
return stack;
}
}
//测试
int main()
{
int flag;
int elem;
linestack *stack = NULL;
puts("-------链栈------");
printf("是否进行入栈或者出栈操作?\n");
while (1) {
printf("\n(0)入栈 (1)出栈 (2)结束!");
scanf("%d", &flag);
if (flag == 0)
{
printf("入栈元素:"); scanf("%d", &elem);
stack = push(stack, elem);
}
else if (flag == 1)
{
printf("\n------出栈操作--------\n");
stack = pop(stack);
}
else
{
printf("\n-------再见-----\n"); break;
}
}
puts("----------------by xj");
return 0;
}
运行结果