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;
}
相关推荐
雾月5510 分钟前
LeetCode 1292 元素和小于等于阈值的正方形的最大边长
java·数据结构·算法·leetcode·职场和发展
Pasregret29 分钟前
访问者模式:分离数据结构与操作的设计模式
数据结构·设计模式·访问者模式
阿让啊2 小时前
C语言中操作字节的某一位
c语言·开发语言·数据结构·单片机·算法
草莓啵啵~2 小时前
搜索二叉树-key的搜索模型
数据结构·c++
丶Darling.3 小时前
26考研 | 王道 | 数据结构 | 第八章 排序
数据结构·考研·排序算法
我也不曾来过14 小时前
list底层原理
数据结构·c++·list
mit6.8245 小时前
[贪心_7] 最优除法 | 跳跃游戏 II | 加油站
数据结构·算法·leetcode
keep intensify5 小时前
通讯录完善版本(详细讲解+源码)
c语言·开发语言·数据结构·算法
shix .6 小时前
2025年PTA天梯赛正式赛 | 算法竞赛,题目详解
数据结构·算法
egoist20236 小时前
【C++指南】告别C字符串陷阱:如何实现封装string?
开发语言·数据结构·c++·c++11·string·auto·深/浅拷贝