如下为栈的链表实现,代码实现了栈的创建、出栈、入栈、计算栈长度、返回栈顶元素、打印栈等功能。运行环境为:Windows 10。集成开发工具为:visual studio 2019。
1.头文件Stack_list.h
#pragma once
#ifndef STACK_LIST_H
#define STACK_LIST_H
struct Node;
typedef struct Node* PtrToNode;
typedef PtrToNode Stack;
typedef int Element;
struct Node
{
Element data;
PtrToNode Next;
};
Stack CreatStack();//创造空栈,并且返回头指针
PtrToNode CreatNode(Element data);//创造结点
int IsEmpty(Stack S);//判断栈是否为空
void MakeEmpty(Stack S);//置空
int LengthOfStack(Stack S);//计算栈长度
void PrintStack(Stack Sr);//打印栈
void Push(Stack S, Element data);//入栈
void Pop(Stack S);//出栈
Element Top(Stack S);//返回栈顶元素
#endif // !STACK_LIST_H
2.源文件Stack_list.c
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include"Stack_list.h"
Stack CreatStack()//创造空栈,并且返回头指针
{
Stack S = malloc(sizeof(struct Node));
if (S == NULL)
{
printf("out of space!!!");
return NULL;
}
S->Next = NULL;
return S;
}
PtrToNode CreatNode(Element data)//创造结点
{
PtrToNode p = malloc(sizeof(struct Node));
if (p == NULL)
{
printf("out of space!!!");
return NULL;
}
else
{
p->data = data;
p->Next = NULL;
}
return p;
}
int IsEmpty(Stack S)//判断栈是否为空
{
return S->Next == NULL;
}
void MakeEmpty(Stack S)//置空
{
if (S == NULL)
{
printf("must use creatstack first!!");
exit(1);
}
else
{
while (!IsEmpty(S))
Pop(S);
}
}
int LengthOfStack(Stack S)//计算栈长度
{
int len = 0;
PtrToNode P = S->Next;
while (P)
{
++len;
P = P->Next;
}
return len;
}
void PrintStack(Stack S)//打印栈
{
PtrToNode P = S->Next;
while (P)
{
printf("%d ", P->data);
P = P->Next;
}
printf("\n");
}
void Push(Stack S, Element data)//入栈
{
PtrToNode P = CreatNode(data);
P->Next = S->Next;
S->Next = P;
}
void Pop(Stack S)//出栈
{
PtrToNode P;
if (IsEmpty(S))
{
printf("there is no element in the stack!!!");
}
else
{
P = S->Next;
S->Next = S->Next->Next;
free(P);
}
}
Element Top(Stack S)//返回栈顶元素
{
if (IsEmpty(S))
{
printf("there is no element in the stack!!!");
return 0;
}
else
{
return S->Next->data;
}
}
3.主程序main.c
#include"Stack_list.h"
int main()
{
Stack S =CreatStack();//创建空栈
for (int i = 0; i < 10; i++)
{
Push(S, i);//入栈
}
PrintStack(S);//打印栈
printf("the length of the stack is: %d\n", LengthOfStack(S));//打印栈长度
printf("the top element of the stack is: %d\n", Top(S));//打印栈顶元素
for (int i = 0; i < 3; i++)
{
Pop(S);//出栈
}
PrintStack(S);
printf("the length of the stack is: %d\n", LengthOfStack(S));
printf("the top element of the stack is: %d\n", Top(S));
return 0;
}
4.运行结果