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;
}
相关推荐
怀旧,13 分钟前
【数据结构】8. 二叉树
c语言·数据结构·算法
凤年徐2 小时前
【数据结构与算法】203.移除链表元素(LeetCode)图文详解
c语言·开发语言·数据结构·算法·leetcode·链表·刷题
浩瀚星辰20243 小时前
C++树状数组详解
java·数据结构·算法
起个数先4 小时前
快速排序算法(Java)
数据结构·排序算法
chao_78912 小时前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
秋说14 小时前
【PTA数据结构 | C语言版】一元多项式求导
c语言·数据结构·算法
谭林杰15 小时前
B树和B+树
数据结构·b树
卡卡卡卡罗特16 小时前
每日mysql
数据结构·算法
chao_78916 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找