用c++程序實現棧

**1.棧的特點:**先進後出,對數組進行操作,每次只能對棧頂元素操作
**2.棧需要的基本操作:**入棧 (push)、出棧(pop)、取棧頂元素(top)。

入棧:在這裏插入圖片描述
出棧:
在這裏插入圖片描述
取棧頂元素:
在這裏插入圖片描述
3.程序實現:
程序說明:
(1)用top來表示當前棧中最上面的元素的下標,用count表示當前棧中所存有的數據個數,由於top總是比count少1,所以Stack類中不用單獨設私有數據top,用(count-1)來表示即可。
(2)Stack_entry:Stack_entry是棧中元素的類型,使用時根據具體情況賦予類型。例如使用時棧中元素爲double類型,則在程序開頭聲明
typedef double Stack_entry;
(3)Error_code:需要寫一個頭文件utility.h ,返回值(enum:枚舉):
enum Error_code { success, fail, range_error, underflow, overflow, fatal, not_present, duplicate_error, entry_inserted, entry_found, internal_error };
代碼:

#include<iostream>
#include"utility.h"

using namespace std;

const int maxstack = 10;  //棧的大小,也就是數組的大小

class Stack {     //定義一個棧的類
public:
   Stack();  //構造函數
   bool empty() const;  //返回值用bool類型,檢測棧中是否有元素,實現過程中並不改變棧中的數據,所以加const。
   Error_code pop();  //刪除棧頂元素
   Error_code top(Stack_entry &item) const;
   //讀取棧頂元素存入item中,實現過程中並不改變棧中的數據,所以加const。“&item”是引用,爲了不必將實參拷貝到形參,節省空間。
   Error_code push(const Stack_entry &item); //向棧中存入一個數據item,爲了節省空間用引用,但是不能改變原有的數據,所以加const。

private:
   int count;  //用來記錄棧中的有效的元素的個數
   Stack_entry entry[maxstack];  //定義一個數組用來存放數據。
};

Error_code Stack::push(const Stack_entry &item)  //入棧
{
   Error_code outcome = success;
   if (count >= maxstack)   //判斷棧中是否已經存滿
      outcome = overflow;    //若已存滿則提示上溢出
   else
      entry[count++] = item;  //若棧中未存滿,則將數據存入棧中
   return outcome;
}

Error_code Stack::pop()  //出棧
{
   Error_code outcome = success;
   if (count == 0)  //判斷棧中是否還有元素
      outcome = underflow; //若沒有則提示下溢出
   else --count;  //若棧中還有元素則count減一,top向下移一個
   return outcome;
}

Error_code Stack::top(Stack_entry &item) const  //取棧頂元素放入item中
{
   Error_code outcome = success;
   if (count == 0) //判斷棧中是否還有元素
      outcome = underflow; //若沒有則提示下溢出
   else
      item = entry[count - 1]; //若棧中還有元素則將棧頂元素值賦入item中
   return outcome;
}

bool Stack::empty() const  //判斷棧是否爲空
{
   bool outcome = true;
   if (count > 0) outcome = false;
   return outcome;
}

Stack::Stack()  //構造函數
{
   count = 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章