《数据结构与程序设计》01-Stacks

用户输入n个元素,由程序给出它的倒序输出。
程序直接包含头文件<stack>,该程序将numbers设置为栈类型,并调用了stack.push(),stack.top(),stack.pop()函数;

#include<stack>
#include<iostream>
using namespace std;

int main(){    
	int n;    
	double item;    
	stack<double> numbers;    
	cout << "Type in an integer n followed by n demical numbers." << endl<< "The numbers will be printed in reverse order." << endl;    
	cin >> n; 
	   
	for(int i = 0; i < n; i++){        
		cin >> item;        
		numbers.push(item);    
	}    
	cout << endl;    

	while (!numbers.empty()){        
		cout << numbers.top() << " ";        
		numbers.pop();    
	}    
	cout << endl;
}

程序输出如下:
pic1

栈的实现:
以数组的形式实现,其中包含构造函数,push()函数,pop()函数,empty()函数,top()函数,还有print()函数;

#include <iostream>
#define MAXSIZE 10
using namespace std;

enum Error_code{      
    success, overflow, underflow
};

typedef char Stack_entry;

class Stack{
private:        
    int count;    	
    Stack_entry Entry[MAXSIZE];
public:
    //构造函数
    Stack(){        
    	count = 0;    
    }
    
    //检验函数是否为空
    bool empty() const{
    	if(count == 0) return true;        
    	else return false;    
    }
    
    //入栈函数
    Error_code push(const Stack_entry & item){
    	Error_code outcome = success;        
    	if (count == (MAXSIZE - 1))             
    		outcome = overflow;
	else{            
		Entry[count] = item;            
		count++;        
	}
        return outcome;    
     }
     
    //出栈函数
    Error_code pop(){        
    	Error_code outcome = success;        
    	if(count == 0)            
    		outcome = underflow;
	else{            
		count--;        
	}        
	return outcome;   
     }
     
     //获得最外面的元素(不对栈产生任何影响)
     Error_code top(Stack_entry & item) const{ 
     	Error_code outcome = success;        
     	if(count == 0)            
     		outcome = underflow;        
     	else            
     		item = Entry[count-1];
        return outcome;    
      }
      
      //打印栈的元素
      void print(){        
      	for(int i = 0;i < count;i++){            
   	   	cout << Entry[i] << "   ";        
      	}   
      }
};

扩展的栈数据结构的顺序实现:
与栈相比,多了full()函数,clear()函数,以及size()函数
因为其他的函数实现与栈相同,这里不再重复

clear(){
    count = 0;
}
	    
//检验函数是不是满
bool full() const{
    if(count >= MAXSIZE) return true;
	return false;	   
}
   
//计算栈的元素个数
int size() const{
    return count;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值