堆栈的链式存储与单链表类似,但其操作收到限制,插入和删除都仅仅在链栈的栈顶进行。
栈顶指针Top,就是表头结点后的第一个结点,我们将它定位栈顶结点
栈底结点的Next为NULL,可依据此关系对堆栈进行遍历
下面是堆栈的链式存储主要操作的基本实现
包括:
1)Stack CreateStack(Stack S):生成空堆栈
2)bool Push(Stack S,ElementType X):将元素X压入堆栈,即压入表头的后一个结点
3)bool IsEmpty(Stack S):链式存储的堆栈只存在空这个状态,不存在满(我也不知道这话对不对,感觉并不严谨)
4)ElementType Pop(Stack S):删除并返回栈顶元素(涉及栈顶结点的释放)
5)int StackLength(Stack S):返回堆栈中元素的个数
6)Stack StackPrint(Stack S):从栈顶到栈底输出堆栈中的各个元素
代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#define Error -1
typedef int ElementType;
typedef struct SNode* PtrToNode;
struct SNode
{
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode Stack;
Stack CreateStack()
{
Stack S = (Stack)malloc(sizeof(struct SNode));
S->Next = NULL;
return S;
}
bool Push(Stack S, ElementType X)
{
Stack TmpCell = (Stack)malloc(sizeof(struct SNode));
TmpCell->Data = X;
TmpCell->Next = S->Next;
S->Next = TmpCell;
return true;
}
bool IsEmpty(Stack S)
{
return (S->Next == NULL);
}
ElementType Pop(Stack S)
{
if (IsEmpty(S))
{
printf("堆栈空\n");
return Error;
}
Stack TmpCell = (Stack)malloc(sizeof(struct SNode));
ElementType X;
TmpCell = S->Next;
X = TmpCell->Data;
S->Next = TmpCell->Next;
free(TmpCell);
return X;
}
int StackLength(Stack S)
{
Stack TempCell = (Stack)malloc(sizeof(struct SNode));
TempCell = S;
int cnt = 0;
while (TempCell->Next != NULL)
{
TempCell = TempCell->Next;
cnt++;
}
return cnt;
}
void StackPrint(Stack S)
{
if (S->Next == NULL)
{
printf("堆栈是空的\n");
return;
}
printf("堆栈内从栈顶到栈底的元素分别为\n");
Stack TempCell = (Stack)malloc(sizeof(struct SNode));
TempCell = S->Next;
while (TempCell != NULL)
{
printf("%d ", TempCell->Data);
TempCell = TempCell->Next;
}
printf("\n");
}
int main()
{
Stack S = CreateStack();
StackPrint(S);
printf("请输入要压进堆栈的元素的个数:\n");
int num;
scanf("%d", &num);
printf("请输入要压进堆栈的各个元素: \n");
while (num--)
{
int number;
scanf("%d", &number);
Push(S, number);
}
printf("弹入后堆栈内的元素的个数为:%d\n", StackLength(S));
StackPrint(S);
printf("此时堆栈内的元素的个数为:%d\n", StackLength(S));
int length = StackLength(S);
printf("从栈顶到栈底依次弹出的元素为: \n");
while (length--)
{
int elem;
printf("%d ", Pop(S));
}
printf("\n");
printf("弹出后堆栈内的元素的个数为:%d\n", StackLength(S));
printf("\n");
return 0;
}