C++ 栈的基本操作

本文介绍了如何使用C++编程实现顺序栈的初始化、入栈、出栈、打印、取栈顶元素、获取栈长度和销毁栈等基本操作。通过链式存储结构,详细阐述了每个操作的实现细节。

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

  1 // zhan.cpp : 定义控制台应用程序的入口点。
  2 //
  3 
  4 #include "stdafx.h"
  5 #include <iostream>
  6 using namespace std;
  7 typedef struct stacknode
  8 {
  9     int data;
 10     struct stacknode *next;
 11 }stacknode,*LinkStack;
 12 
 13 //判断栈为空
 14 int StackEmpty(LinkStack &top)
 15 {
 16     if(top ->next == NULL)
 17         return 1;
 18     else 
 19         return 0;
 20 }
 21 
 22 //入栈函数
 23 LinkStack push(LinkStack &top,int value)
 24 {
 25     LinkStack p = new stacknode;
 26     if(p != NULL)
 27     {
 28         p ->data = value;//可以理解为在链表尾部插入一个节点。
 29         p ->next = top ->next;
 30         top ->next = p;
 31     }
 32     else 
 33         cout << "没有内存可分配" << endl;
 34     return top;
 35 }
 36 
 37 //出栈函数
 38 int pop(LinkStack &top)
 39 {
 40     LinkStack temp = new stacknode;
 41     int data;
 42     if(StackEmpty(top))
 43         cout << "该栈为空!" << endl;
 44     else 
 45     {
 46         temp = top ->next;//可以理解为删除一个节点
 47         data = temp ->data;
 48         top ->next = temp ->next;
 49         delete(temp);
 50     }
 51     return data;
 52 }
 53 
 54 //打印函数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值