2024.6.18.exercise

cpp 复制代码
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

// 栈
//typedef struct stack
//{
//	int* data;
//	int top;
//}stack;
//
//void initstack(stack* s, int size)
//{
//	s->top = -1;
//	s->data = (int*)malloc(sizeof(int) * size);
//}
//
//void push(stack* s, int element, int size)
//{
//	if (s->top >= size - 1)
//	{
//		printf("栈已满\n");
//		return;
//	}
//	s->data[++s->top] = element;
//}
//
//int pop(stack* s)
//{
//	if (s->top == -1)
//	{
//		printf("is empty\n");
//		return -5;
//	}
//	return s->data[s->top--];
//}
//
//int main()
//{
//	printf("你想要多大的栈?\n");
//	int size;
//	scanf("%d" , &size);
//	stack s;
//	initstack(&s, size);
//	printf("有多少元素要入栈?\n");
//	int n;
//	scanf("%d", &n);
//	int i;
//	for (i = 0; i < n; i++)
//	{
//		printf("请输入第%d个元素\n",i+1
//		);
//		int element;
//		scanf("%d", &element);
//		push(&s, element, size);
//	}
//	for (i = 0; i < n; i++)
//	{
//		printf("%d ", pop(&s));
//	}
//	return 0;
//}


typedef struct stack
{
	int data;
	struct stack* next;
}stack;

bool isempty(stack* top)
{
	if (top == NULL)
	{
		return true;
	}
	return false;

}

stack* creatnewnode(int element)
{
	stack* newnode = (stack*)malloc(sizeof(stack));
	if (newnode == NULL)
	{
		printf("NULL\n");
		return NULL;
	}
	newnode->data = element;
	newnode->next = NULL;
	return newnode;
}

void push(stack** top, int element)
{
	stack* newnode = creatnewnode(element);
	newnode->next = *top;
	*top = newnode;
}

int pop(stack** top)
{
	if (isempty(*top))
	{
		printf("empty\n");
		return -36200;
	}
	stack* temp;
	temp = *top;
	int poped;
	poped = temp->data;
	*top = temp->next;
	return poped;
}

int main()
{
	stack* top = NULL;
	if (!isempty(top))
	{
		printf("init failed\n");
		return - 1;
	}
	printf("请输入有几个元素要入栈?\n");
	int n;
	scanf("%d", &n);
	int i = 0;
	for (i = 0; i < n; i++)
	{
		printf("请输入第%d个元素\n", i + 1);
		int element;
		scanf("%d", &element);
		push(&top, element);
	}
	for (i = 0; i < n; i++)
	{
		printf("%d ", pop(&top));
	}
	return 0;
}
相关推荐
Tim_1019 小时前
【算法专题训练】17、双向链表
数据结构·c++·算法·链表
ZCollapsar.19 小时前
数据结构 04(线性:双向链表)
c语言·数据结构·学习·算法·链表
YA10JUN19 小时前
数据结构基础--最小生成树
数据结构·算法·图论
lifallen20 小时前
深入了解Flink核心:Slot资源管理机制
大数据·数据结构·数据库·算法·flink·apache
序属秋秋秋20 小时前
《C++进阶之STL》【红黑树】
开发语言·数据结构·c++·笔记·学习·stl
.桂花载酒.20 小时前
数据结构8---排序
数据结构
lifallen1 天前
Caffeine TimerWheel时间轮 深度解析:O(1)复杂度增删和触发时间事件
java·数据结构·算法·缓存·中间件
island13141 天前
【Redis#7】Redis 数据结构 -- Set 类型
java·数据结构·redis
学涯乐码堂主1 天前
《信息学奥林匹克辞典》中的一个谬误
数据结构·c++·算法·青少年编程·排序算法·信奥·gesp 考试
笨笨的摸索1 天前
变量在静态与动态类型语言中的区别
数据结构·经验分享