C/C++ 知识回顾 栈的入栈与出栈

本文介绍了一个简单的栈数据结构实现方法,使用C++编程语言通过结构体定义节点与栈,并提供了入栈(push)与出栈(pop)的操作实现。该实现考虑了空栈情况及如何在非空栈中正确进行元素的添加与移除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
using namespace std;
typedef struct student
{
	int data;
	struct student * next;
}node;

typedef struct stackqueque
{
	node * top, *zhandi;
} Stack;

Stack * push(Stack * stack,int num)
{
	node *s = (node *)malloc(sizeof(node));
	s->data = num;
	s->next = NULL;
	if (stack->top==NULL)
	{
		stack->top = s;
		stack->zhandi = s;
	}
	else
	{
		stack->top->next = s;
		stack->top = s;
	}
	return stack;
}
int  pop(Stack *stack)
{
	if (stack->top==NULL)
	{
		cout << "栈为空" << endl;
		return -1;
	}
	if (stack->top==stack->zhandi)
	{
		int x = stack->top->data;
		stack->top = NULL;
		stack->zhandi = NULL;
		return x;
	}
	else
	{
		
		node*	p = stack->zhandi;
		while (p->next!=stack->top)
		{
			p = p->next;
		}
		node *q = stack->top;
		int x = stack->top->data;
		p->next = NULL;
		stack->top = p;
		free(q);
		return x;

	}
	
}
int main()
{

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值