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

本篇博客记录链栈的基本操作,无聊的时候打发时间写的,防止时间长了不写写就忘没了(づ ●─● )づ

head.h:

#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <Windows.h>

 demo.c:

#include "head.h"
/*
	链栈建立
		
		建立栈结构体
		建立top头指针
		
		链栈的插入
		链栈的删除
		链栈的查看
		链栈的清空 
		链栈长度的计算

		链栈的判空
*/

//建立栈结构体
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("插入信息请输入1\n删除信息请输入2\n所有信息查看情输入3\n删除全部信息请输入4\n信息个数查看请输入5\n退出系统请输入6\n");
		scanf_s("%d",&i);
		switch (i)
		{
		case 1:
			//链栈的插入
			while (while_2)
			{
				addStack(top);

				printf("***是否要继续输入***\n继续输入请输入0\n");
				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("姓名:%s\t年龄:%d\n", 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("长度为:%d\n",number + 1);

	free(q);
}

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

活成自己的样子啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值