栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【数据结构 链栈】c语言|入栈|出栈|清空栈|查看栈|算栈长

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【数据结构 链栈】c语言|入栈|出栈|清空栈|查看栈|算栈长

本篇博客记录链栈的基本操作,无聊的时候打发时间写的,防止时间长了不写写就忘没了(づ ●─● )づ head.h:
#pragma once
#include 
#include 
#include 
#include 
 demo.c:
#include "head.h"


//建立栈结构体
typedef struct Node
{
	char name[20];
	int age;
	struct Node* next;
}List;

//函数
//链栈的增加
void addStack(List top);
//链栈的删除
void outStack(List top);
//链栈的查看
void lookStack(List top);
//链栈的清空
void cleanStack(List top);
//链栈长度的计算
void lengthStack(List top);
//栈判空
int judgeStack(List top);

int main(void)
{
	int while_1 = 1, while_2 = 1;
	int judge;
	int i;

	//建立top头指针
	List top;
	top.next = NULL;
	while (while_1)
	{
		printf("插入信息请输入1n删除信息请输入2n所有信息查看情输入3n删除全部信息请输入4n信息个数查看请输入5n退出系统请输入6n");
		scanf_s("%d",&i);
		switch (i)
		{
		case 1:
			//链栈的插入
			while (while_2)
			{
				addStack(top);

				printf("***是否要继续输入***n继续输入请输入0n");
				scanf_s("%d", &judge);
				if (judge == 0)
				{
					break;
				}
			}
			break;

		case 2:
			//链栈的删除
			printf("***只能删除栈头***");
			outStack(top);
			break;

		case 3:
			//链栈的查看
			lookStack(top);
			break;

		case 4 :
			//链栈的清空
			cleanStack(top);
			break;

		case 5:
			//链栈长度的计算
			lengthStack(top);
			break;

		case 6:
			printf("已经退出系统n");
			exit(0);
		}
	}
	return 0;
}

//链栈的增加
void addStack(List top)
{
	List* s;
	s = (List*)malloc(sizeof(List));

	printf("***请输入新学生的姓名***n");
	scanf_s("%s",&s->name,20);
	printf("***请输入新学生的年龄***n");
	scanf_s("%d",&s->age);

	s->next = top.next;
	top.next = s;
	
	printf("***数据已经添加***n");
}

//链栈的删除
void outStack(List top)
{
	if (judgeStack(top) == 0)//栈空
	{
		printf("栈已空,不需要删除n");
	}
	else
	{
		top.next->next = top.next;
	}
}

//链栈的查看
void lookStack(List top)
{
	List* p = NULL;
	p = (List*)malloc(sizeof(List));
	p->next = top.next;

	if (top.next != NULL)
	{
		printf("栈中无数据n");
	}
	else
	{
		while(true)
		{
			printf("姓名:%st年龄:%dn", p->name, p->age);
			p = p->next;
			if (p->next == NULL)
			{
				break;
			}
		}
	}

}

//链栈的清空
void cleanStack(List top)
{
	while (1)
	{
		if (judgeStack(top) == 0)//栈空
		{
			printf("栈已空,不需要删除n");
		}
		else
		{
			top.next->next = top.next;
		}
	}

	printf("栈已经清空n");

}

//链栈长度的计算
void lengthStack(List top)
{
	int number = 0;
	List* q;
	q = (List*)malloc(sizeof(List));
	q->next = top.next;

	for (; q->next != NULL;)
	{
		number++;
		q = q->next;
	}
	printf("长度为:%dn",number + 1);

	free(q);
}

//栈判空
int judgeStack(List top)
{
	if (top.next != NULL)
	{
		return 1;//栈非空
	}
	else
	{
		return 0;//栈空
	}
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/942334.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号