c++创建栈及部分函数实现

 1 // 栈的创建.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include<iostream>
 6 using namespace std;
 7 const int size=100;     //初始空间分配
 8 const int increase=10;  //增补空间量
 9 
10 typedef struct stack{    
11     int *elem;     //存储数据元素的数组
12     int top;      //栈顶指针
13 };   //建立一个栈的结构体
14 
15 //构建一个空栈s
16 void create(stack &s)
17 {
18     s.elem=new int[size];   
19     s.top=-1;
20 }
21 
22 //判断栈是否为空
23 bool empty(stack s)
24 {    
25     if(s.top==-1)return true;
26     else return false;
27 }
28 
29 //输出栈顶元素
30 int gettop(stack s,int &e)
31 {
32     if(s.top==-1)return false;  //若占空(无栈顶元素)则出错
33     else e=s.elem[s.top];
34     return e;
35 }
36 
37 //入栈,向栈内添加元素
38 void push(stack &s,int e)
39 {    
40     if(s.top==size-1)cout<<"空间不足"<<endl; //若栈满,则增加空间
41     s.top++;
42     s.elem[s.top]=e;
43 }
44 
45 //若栈非空,删除栈顶元素并用e返回其值
46 int pop(stack &s,int&e)
47 {    
48     if(s.top==-1)return false;  //若栈空,则报错
49     e=s.elem[s.top];   //等价于e=s.elem[s.top--]
50     s.top--;
51     return e;
52 }

 

posted on 2013-05-08 13:57  之足常乐  阅读(701)  评论(0)    收藏  举报

导航