栈的链式储存
这里和基本栈(代码见栈的基本操作一)做一个小小的链接,便于理解。
其实核心代码也就是这个思路
FIRST:带头节点的
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct Linknode {
ElemType data;
struct Linknode* next;
}*LiStack;//Linknode,*LiStack;
void InitStack(LiStack& L)
{
L = (Linknode*)malloc(sizeof(LiStack));
L->next = NULL;
}
bool StackEmpty(LiStack L)
{
if (L->next == NULL)
return true;//空栈
else
return false;
}
bool InsertNextNode(LiStack &L,ElemType x)//链栈进栈不用判断栈是否满了
{
LiStack s;
s = (Linknode*)malloc(sizeof(LiStack));
s->data = x;
s->next = L->next;
L->next = s;
return true;
}
bool DelectNextNode(LiStack& L, ElemType &x)//出栈,删除头节点后的数据;得到栈顶元素的操作一致
{
if (StackEmpty(L))
return false;
x = L->next->data;
L->next= L->next->next;//这里注意不要写成L= L->next->next
printf("%-3d", x);
return true;
}
void Printf(LiStack L)
{
int x = -1;
while (!StackEmpty(L))
{
DelectNextNode(L, x);
}
}
//1 3 5 7 9 12 13 999
int main()
{
LiStack L;
ElemType x;
InitStack(L);
scanf("%d", &x);
while (x != 999)
{
InsertNextNode(L, x);
scanf("%d", &x);
}
Printf(L);
return 0;
}
SECOND:不带头节点的
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct Linknode {
ElemType data;
struct Linknode* next;
}*LiStack;//这样写也可以:Linknode,*LiStack;
void InitStack(LiStack& L)
{
L= NULL;
}
bool StackEmpty(LiStack L)
{
if (L== NULL)
return true;//空栈
else
return false;
}
bool InsertNextNode(LiStack& L )//链栈进栈不用判断栈是否满了
{
ElemType x;
LiStack s, r;
scanf("%d", &x);
if (x != 999)
{
L = (Linknode*)malloc(sizeof(LiStack));
L->data = x;
L->next = NULL;
scanf("%d", &x);
while (x != 999)
{
s = (Linknode*)malloc(sizeof(LiStack));
s->data = x;
s->next = L;
L = s;
scanf("%d", &x);
}
}
return true;
}
bool DelectNextNode(LiStack& L, ElemType& x)//出栈,删除头节点后的数据;得到栈顶元素的操作一致
{
if (StackEmpty(L))
return false;
x = L->data;
L= L->next;//这里注意不要写成L= L->next->next
printf("%-3d", x);
return true;
}
void Printf(LiStack L)
{
int x = -1;
while (!StackEmpty(L))
{
DelectNextNode(L, x);
}
}
//1 3 5 7 9 12 13 999
int main()
{
LiStack L;
ElemType x;
InitStack(L);
InsertNextNode(L);
Printf(L);
return 0;
}