顺序栈的实现依靠数组,而数组需要事先声明长度,一次性地静态地分配内存空间。这样就给我们带来很多不便。因为我们事先并不能精确地估计栈所需的大小,估计大了浪费空间,估计小了后果就严重了,导致程序无法正常运行。所以我们通常使用链栈这种数据结构。
链栈用链表作为存储结构,栈初始化时仅需给栈顶指针分配内存空间,而后每当有数据入栈时再为该数据分配空间,这样实现了内存空间的动态分配。理论上栈的大小可以是无限大的(小心撑爆你的内存)。不存在顺序栈的诸多问题。
链栈将栈顶top看作头结点,链栈的创建就是头插法创建链表
程序实现:依次把0-9压栈,再依次出栈并打印。
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
/*** 链栈:相当于头插法的链表 ***/
#if 0
typedef int ElementType;
typedef struct node {
ElementType data;
struct node *next;
} StackNode, *LinkStack;
void InitStack(LinkStack top)
{
top->next = NULL;
}
int IsEmpty(LinkStack top)
{
if (top->next == NULL) return TRUE;
return FALSE;
}
int Push(LinkStack top, ElementType element)
{
StackNode *temp;
temp = (StackNode *)malloc(sizeof(StackNode));
if (temp == NULL) return FALSE;
temp->data = element;
temp->next = top->next;
top->next = temp;
return TRUE;
}
int Pop(LinkStack top, ElementType *element)
{
if (IsEmpty(top)) return FALSE;
StackNode *temp = top->next;
*element = temp->data;
top->next = temp->next;
free(temp);
return TRUE;
}
void GetTop(LinkStack top, ElementType *element)
{
*element = top->next->data;
}
void main()
{
LinkStack S;
S = (LinkStack)malloc(sizeof(StackNode));
InitStack(S);
for (int i=0; i<100; ++i)
{
Push(S, i);
}
int iValue;
while (!IsEmpty(S))
{
Pop(S, &iValue);
printf(" %d ", iValue);
}
system("pause");
return;
}
#endif
/* 链栈的初始化、出栈、入栈、取顶元素、判断栈顶是否为空 */
typedef int ElemType;
typedef struct LinkStack
{
ElemType data;
struct LinkStack *next;
} LStack;
/* 链栈的初始化 */
void InitStack(LStack *top)
{
top->next = NULL;
}
/* 栈是否为空 */
bool IsEmpty(LStack *top)
{
if (top->next == NULL) return TRUE;
return FALSE;
}
/* 取链栈栈顶元素 */
int GotTop(LStack *top, ElemType &value)
{
if (!IsEmpty(top))
{
value = top->next->data;
return value;
}
else exit(1);
}
bool Push(LStack *top, ElemType &value)
{
if (top == NULL) exit(1);
LStack *temp = (LStack *)malloc(sizeof(LStack));
if (temp == NULL) return FALSE;
temp->data = value;
temp->next = top->next;
top->next = temp;
return TRUE;
}
void Pop(LStack *top)
{
ElemType iValue;
LStack *temp;
temp = top->next;
if (!IsEmpty(top))
{
iValue = temp->data;
top->next = temp->next;
printf(" %d ",iValue);
free(temp);
}
else
{
exit(1);
}
}
int main()
{
LStack *top;
top = (LStack *)malloc(sizeof(LStack));
InitStack(top);
for (int i=0; i<10; ++i)
{
Push(top, i);
}
printf("输出链栈元素 !\n");
while (!IsEmpty(top))
{
Pop(top);
}
printf("\n");
system("pause");
return 0;
}