栈的链式表示和实现:
编写一个程序实现链栈(带头节点)的各种基本运算,并在此基础上设计一个主程序,完成如下功能:
- 初始化链栈
- 入栈
- 出栈
- 判断栈是否为空
- 获取链栈长度
- 取栈顶元素
- 遍历链栈
- 链栈置空
代码(C语言):
/*链栈的实现及常用操作测试*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
/*链栈的数据结构*/
typedef int ElemType;
typedef struct Node
{
ElemType data;
struct Node* next;
} Node, * LinkStack;
/*函数声明列表*/
LinkStack InitLinkStack(); //1 初始化链栈
int StackEmpty(LinkStack S); //2 判断链栈是否为空
int StackLength(LinkStack S); //3 获取链栈长度
int PushLinkStack(LinkStack S, ElemType e); //4 入栈
int PopLinkStack(LinkStack S, ElemType* e); //5 出栈
void PrintLinkStack(LinkStack S); //6 遍历栈(从栈顶到栈底)
void ClearLinkStack(LinkStack S); //7 链栈置空
int GetTopLinkStack(LinkStack S, ElemType* e); //8 取栈顶元素
/*主函数*/
int main(void)
{
ElemType e;
printf("初始化链栈成功!\n");
LinkStack S = InitLinkStack();
int i = 0;
printf("\n执行9次入栈操作!\n");
for (i = 0; i < 9; i++)
{
PushLinkStack(S, i + 1);
}
printf("执行完毕!当前栈长度为:%d\n打印当前栈:", StackLength(S));
PrintLinkStack(S);
printf("\n执行4次出栈操作!\n");
for (i = 0; i < 4; i++)
{
PopLinkStack(S, &e);
printf("第%d次:栈顶元素%d出栈成功!\n", i + 1, e);
}
printf("执行完毕!当前栈长度为:%d\n打印当前栈:", StackLength(S));
PrintLinkStack(S);
GetTopLinkStack(S, &e);
printf("\n执行取栈顶元素操作:当前栈顶元素为:%d\n", e);
printf("\n执行清空栈操作!\n");
ClearLinkStack(S);
if (StackEmpty(S)) printf("执行完毕!当前栈为空!\n");
else printf("清空栈失败!\n");
return 0;
}
/*函数实现部分*/
/*【功能1 初始化链栈(带头结点的链栈)】*/
LinkStack InitLinkStack()
{
LinkStack S = (LinkStack)malloc(sizeof(Node));
S->next = NULL;
return S;
}
/*【功能2 判断链栈是否为空】*/
int StackEmpty(LinkStack S)
{
if (S == NULL) return 0;
return S->next == NULL;
}
/*【功能3 获取链栈长度】*/
int StackLength(LinkStack S)
{
int len = 0;
if (StackEmpty(S)) return 0;
Node* p = S->next; // 带头结点的链栈要先移动一下
while (p != NULL)
{
len++;
p = p->next;
}
return len;
}
/*【功能4 入栈】*/
int PushLinkStack(LinkStack S, ElemType e)
{
// 分配入栈结点
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) return 0; // 结点分配失败
// 跟单链表一样使用头插法
newNode->data = e;
newNode->next = S->next;
S->next = newNode;
return 1; //入栈成功则返回1
}
/*【功能5 出栈】*/
int PopLinkStack(LinkStack S, ElemType* e)
{
if (StackEmpty(S)) return 0; //栈空则出栈失败
Node* top = S->next; //访问栈顶结点
*e = top->data; //取出栈顶元素
S->next = top->next;
free(top); //释放栈顶空间
return 1; //出栈成功则返回1
}
/*【功能6 遍历栈(从栈顶到栈底)】*/
void PrintLinkStack(LinkStack S)
{
Node* p = S->next; //遍历时从首元素节点开始
while (p)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
/*【功能7 链栈置空】*/
void ClearLinkStack(LinkStack S)
{
Node* p = S->next;
while (p)
{
Node* q = p;
p = p->next;
free(q);
}
S->next = NULL;
}
/*【功能8 取栈顶元素】*/
int GetTopLinkStack(LinkStack S, ElemType* e)
{
if (StackEmpty(S)) return 0; //如果为空栈则返回0,代表取栈顶元素失败
else
{
*e = S->next->data;
return 1; //返回1代表取栈顶元素成功,栈顶元素保存在e中
}
}