链栈就是采用链表来存储栈。链栈示意图如下。
一般用带头结点的单链表实现
链栈主要是入栈和出栈操作。入栈其实就是链表的头插法
入栈示意图:
出栈示意图:
----------------------------------------------------------------------------------------------------------------------------------
完整代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define maxsize 100
/******************链栈结点定义****************/
typedef struct LNode
{
int data; //数据域
struct LNode *next; //指针域
}StackNode;
/*******************输入进栈所需数字****************/
int a[maxsize] = { 0 };
int count = 0;
int InData()
{
int i = 0;
printf("请输入数据,按回车键结束\n");
while (1)
{
scanf_s("%d", &a[i]);
i++;
count++;
char c = getchar();
if (c == '\n')
break;
}
return count;
}
StackNode *lst; //作为全局变量
StackNode *head;
StackNode *top;
int icount = 0;
/*********************入栈*********************/
int push(StackNode *lst)
{
lst = NULL; //初始化
head = (StackNode*)malloc(sizeof(StackNode)); //申请头结点
head->next = NULL;
StackNode *p = (StackNode*)malloc(sizeof(StackNode));
p->next = NULL;
printf("入栈顺序为:");
for (int i = 0; i < count; i++)
{
top = (StackNode*)malloc(sizeof(StackNode)); //栈顶指针
top->next = NULL;
top->data = a[i];
top->next = p->next;
p->next = top;
icount++;
printf("%d ", top->data);
}
return lst;
}
/*********************出栈*****************/
int pop(lst)
{
if (lst == NULL)
return 0;
printf("\n出栈顺序为:");
for (int i = 0; i < icount; i++)
{
printf("%d ", top->data);
head->next = top->next;
free(top);
top = head->next;
}
}
int main()
{
InData();
push(&lst);
pop(&lst);
system("pause");
}
结果图如下: