鏈式棧(c++實現)

棧的特點是後進先出。

【頭文件linkstack.h】

// linkstack.h代碼
template<class T>class Linkstack;
template<class T>
class stacknode
{
friend class Linkstack<T>;
private:
  T data;
 stacknode<T> *next;
};
template<class T>
class Linkstack
{
public:
    Linkstack():top(0){}; //利用構造函數初始化棧(空)
    ~Linkstack();
    bool Isempty()const; //const成員函數不會修改數據成員
    void push(T item);
    void pop();
    T Top()const;
    void show();
private:
     stacknode<T> *top;
};
/*---------判斷棧是否爲空-------*/
template<class T>
bool Linkstack<T>::Isempty()const
{
   return top==0;
}
/*---------元素進棧-------*/
template<class T>
 void Linkstack<T>::push(T item)
 {
   stacknode<T> *p=new stacknode<T>();
   cout<<item<<"進棧"<<endl;
   p->data=item;
   p->next=top;
   top=p;

 }
/*---------棧頂元素出棧-------*/
template<class T>
void Linkstack<T>::pop()
{
  if(Isempty())
  {
    cout<<"棧爲空"<<endl;
  }
  else
  {  
      stacknode<T> *p=top;
      cout<<top->data<<"出棧"<<endl;
      top=top->next;
      delete p;          //防止內存泄露
   /*內存泄露:用動態存儲分配函數動態開闢的空間,在使用完畢後未釋放,結果導致一直佔據該內存單元 */
  }
}
/*---------獲取棧頂元素-------*/
template<class T>
T Linkstack<T>::Top()const
{
   if(Isempty())
  {
      throw "棧爲空";
  }
  else
  {
    return top->data;
  }
}
/*---------輸出棧中的所有元素-------*/
template<class T>
void Linkstack<T>::show()
{
 stacknode<T> *p=top;
 if(Isempty())
  {
    cout<<"棧爲空"<<endl;
  }
 else
 {
   cout<<"此時棧中元素爲:";
   while(p)
   {
    cout<<p->data<<" ";
    p=p->next;
    }
    cout<<endl;
  }
}
/*-----利用析構函數釋放空間-----*/
template<class T>
Linkstack<T>::~Linkstack()  
{
  while(!Isempty())
  {
    pop();  //調用pop函數依次釋放棧元素
  }
}

#endif

【主程序】

//main.cpp代碼
#include "linkstack.h"
#include<iostream>
using namespace std;
int main()
{
  Linkstack<int> L;
  L.push(1);
  L.push(2);
  L.push(3);
  L.push(4);
  L.show();
  cout<<"棧頂元素爲:"<<L.Top()<<endl;

  L.pop();
  cout<<"棧頂元素爲:"<<L.Top()<<endl;

   L.push(5);
  cout<<"棧頂元素爲:"<<L.Top()<<endl;

  system("pause");
  return 0;
}

【結果圖】

這裏寫圖片描述

發佈了64 篇原創文章 · 獲贊 29 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章