栈的链表(C语言)实现

如下为栈的链表实现,代码实现了栈的创建、出栈、入栈、计算栈长度、返回栈顶元素、打印栈等功能。运行环境为: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.运行结果
在这里插入图片描述

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值