数据结构中栈的相关操作(链栈)

功能说明

代码为顺序栈的相关操作,主要操作为创建链栈、入栈、出栈、获取链栈长度以及打印链栈中的元素等功能。代码由头文件(LinkStack.h)、接口实现(LinkStack.c)和测试文件(main.c)三部分组成。
LinkStack.h

#ifndef __LINKSTACK__
#define __LINKSTACK__
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#pragma warning(disable:4996)
typedef int Elemtype;
typedef struct LNode
{
	Elemtype data;
	struct LNode *next;
}LNode,*LinkStack;
LinkStack CreateLinkStack(LinkStack L);
LinkStack Push(LinkStack L, Elemtype x);
int LengthStack(LinkStack L);
LNode* Pop(LinkStack L);
void PrintStack(LinkStack L);
#endif

LinkStack.c

#include"LinkStack.h"
LinkStack CreateLinkStack(LinkStack L)
{
	L = (LinkStack)malloc(sizeof(LNode));
	if (L == NULL)
	{
		return NULL;
	}
	L->next = NULL;
	L->data = -1;
	return L;
}
LinkStack Push(LinkStack L, Elemtype x)
{
	LinkStack temp = (LNode*)malloc(sizeof(LNode));
	if (temp == NULL)
	{
		printf("申请内存失败!\n");
		return NULL;
	}
	temp->data = x;
	temp->next = L->next;
	L->next = temp;
	return L;
}
int LengthStack(LinkStack L)
{
	int i = 0; 
	LinkStack temp = L->next;
	while (temp != NULL)
	{
		i++;
		temp = temp->next;
	}
	return i;
}
LNode* Pop(LinkStack L)
{
	LinkStack temp;
	if (L->next == NULL)
	{
		return NULL;
	}
	temp = L->next;
	L->next = temp->next;
	return (LNode*)temp;
}
void PrintStack(LinkStack L)
{
	LinkStack temp  = L->next;
	if (L->next == NULL)
	{
		return;
	}
	printf("栈中元素为: ");
	while (temp != NULL)
	{
		printf("%d ", temp->data);
		temp = temp->next;
	}
	printf("\n");
}

main.c

#include"LinkStack.h"
int main(int argc, const char* argv[])
{
	LinkStack L = NULL;
	LNode *temp = NULL;
	int len,i;
	L = CreateLinkStack(L);
	for (i = 0; i < 10; i++)
	{
		L = Push(L, i);
	}
	len = LengthStack(L);
	printf("栈的长度为%d\n", len);
	temp = Pop(L);
	printf("出栈元素为%d\n", temp->data);
	PrintStack(L);
	return 0;
}

运行结果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值