国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

C++實現鏈式棧的代碼

2020-02-24 14:24:29
字體:
來源:轉載
供稿:網友

你知道如何用C++實現鏈式棧嗎?在學習C語言的過程中我們難免會需要使用鏈式棧,但是有很多小伙伴們吧知道C++實現鏈式棧的代碼,那么接下來的內容中小編就將為大家介紹具體的實現方法。

?

// MyStack.cpp : 定義控制臺應用程序的入口點。
//自己構造一個鏈式棧,具有push(入棧),pop(出棧),top(取得棧頂元素),size(返回棧大小),empty(判斷是否為空)等功能
#include "stdafx.h"
#include <iostream>
using namespace std;
//構造棧的節點
template <class T>
struct NODE
{
?NODE<T>* next;
?T data;
};
template <class T>
class MyStack
{
public:
?MyStack()
?{
??phead = new NODE<T>;
??if (phead == NULL)
??{
???cout << "Failed to malloc a new node. " << endl;
??}
??else
??{
???phead->data = NULL;
???phead->next = NULL;
??}
?}

?//入棧
?void push(T e)
?{
??NODE<T>* p = new NODE<T>;
??if (p == NULL)
??{
???cout << "Failed to malloc a new node. " << endl;
??}
??else
??{
???p->data = e;
???p->next = phead->next;
???phead->next = p;
??}
?}

?//出棧
?T pop()
?{
??T e;
??NODE<T>* p = phead->next;
??if(p != NULL)
??{
???phead->next = p->next;
???e = p->data;
???delete p;
???return e;
??}
??else
??{
???cout << "There is no elements in the stack." << endl;
???return NULL;
??}
?}

?//取得棧頂元素
?T top()
?{
??T e;
??NODE<T>* p = phead->next;
??if (p != NULL)
??{
???e = p->data;
???return e;
??}
??else
??{
???cout << "There is no elements in the stack." << endl;
???return NULL;
??}
?}
?//取得棧中元素個數
?int size()
?{
??int count(0);
??NODE<T>* p = phead->next;
??while (p != NULL)
??{
???p = p->next;
???count++;
??}
??return count;
?}
?//判斷stack是否為空
?bool empty()
?{
??NODE<T>* p = phead;
??if (p->next == NULL)
??{
???return true;
??}
??else
??{
???return false;
??}
?}
private:
?NODE<T>* phead;
};
int _tmain(int argc, _TCHAR* argv[])
{
?MyStack<int> sta;
?sta.push(1);
?sta.push(2);
?sta.push(3);
?cout << "The size of the stack now is " << sta.size() << endl;
?sta.pop();
?cout << "The top element is " << sta.top() << endl;
?cout << "The size of the stack now is" << sta.size() << endl;
?if (sta.empty())
?{
??cout << "This stack is empty." << endl;
?}
?else
?{
??cout << "This stack is not empty." << endl;
?}
?return 0;
}

以上就是小編對于C++實現鏈式棧的代碼的介紹,看完后大家是否都了解了呢?如果你覺得小編介紹的有不足的地方,歡迎大家指正。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 固镇县| 涟源市| 宁乡县| 视频| 方山县| 玉树县| 连城县| 佛山市| 湟中县| 札达县| 霍州市| 昔阳县| 报价| 定兴县| 新昌县| 吉安县| 札达县| 古蔺县| 塔城市| 姚安县| 崇阳县| 莱州市| 响水县| 措美县| 牟定县| 沧源| 延边| 赤水市| 九龙城区| 西贡区| 陈巴尔虎旗| 新平| 朔州市| 高平市| 都匀市| 民丰县| 济南市| 苏尼特右旗| 历史| 繁峙县| 新晃|