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;
}
相关推荐
梭七y3 小时前
【力扣hot100题】(103)移动零
数据结构·算法·leetcode
H CHY4 小时前
C++代码
c语言·开发语言·数据结构·c++·算法·青少年编程
xiaolang_8616_wjl4 小时前
c++题目_传桶(改编于atcoder(题目:Heavy Buckets))
数据结构·c++·算法
历程里程碑6 小时前
双指针巧解LeetCode接雨水难题
java·开发语言·数据结构·c++·python·flask·排序算法
橘颂TA7 小时前
【剑斩OFFER】算法的暴力美学——链表相加(二)
数据结构·链表·牛客·结构与算法
报错小能手7 小时前
数据结构 可扩展哈希
数据结构·哈希算法·散列表
AI科技星7 小时前
宇宙的像素:真空中一点如何编码无限星光
数据结构·人工智能·算法·机器学习·重构
王璐WL8 小时前
【数据结构】二叉树经典算法题和选择题
数据结构·算法
jllllyuz8 小时前
MATLAB多目标优化:SQP算法实现
数据结构·算法·matlab
im_AMBER8 小时前
数据结构 14 【复习】二叉树中序遍历 | 线索二叉树 | 树、森林、二叉树的转换 | 层次遍历二叉树
数据结构·笔记·学习·算法