C++利用鏈表寫一個(gè)簡(jiǎn)單的棧實(shí)例詳解
更新時(shí)間:2017年05月25日 08:59:35 作者:huplion
這篇文章主要介紹了C++利用鏈表寫一個(gè)簡(jiǎn)單的棧實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下
C++中其實(shí)有stack的模板類。功能更為強(qiáng)大。
自己寫一個(gè)棧能讓我們對(duì)棧這種數(shù)據(jù)結(jié)構(gòu)更加熟悉。這個(gè)棧有一個(gè)不足之處就是里面存放的元素類型只能為int。
#include <iostream>
using namespace std;
class Stack
{
private:
struct Node
{
int data;
Node *next;
};
Node *head;
Node *p;
int length;
public:
Stack()
{
head = NULL;
length = 0;
}
void push(int n)//入棧
{
Node *q = new Node;
q->data = n;
if (head == NULL)
{
q->next = head;
head = q;
p = q;
}
else
{
q->next = p;
p = q;
}
length ++;
}
int pop()//出棧并且將出棧的元素返回
{
if (length <= 0)
{
abort();
}
Node *q;
int data;
q = p;
data = p->data;
p = p->next;
delete(q);
length --;
return data;
}
int size()//返回元素個(gè)數(shù)
{
return length;
}
int top()//返回棧頂元素
{
return p->data;
}
bool isEmpty()//判斷棧是不是空的
{
if (length == 0)
{
return true;
}
else
{
return false;
}
}
void clear()//清空棧中的所有元素
{
if (length > 0)
{
pop();
}
}
};
int main()
{
//以下為測(cè)試代碼
Stack s;
s.push(1);
s.push(2);
s.push(3);
while(!s.isEmpty())
{
cout<<s.pop()<<endl;
}
return 0;
}
對(duì)這段代碼稍加修改,這個(gè)棧就能存放其他類型的元素
#include <iostream>
using namespace std;
template<class T>class Stack
{
private:
struct Node
{
T data;
Node *next;
};
Node *head;
Node *p;
int length;
public:
Stack()
{
head = NULL;
length = 0;
}
void push(T n)//入棧
{
Node *q = new Node;
q->data = n;
if (head == NULL)
{
q->next = head;
head = q;
p = q;
}
else
{
q->next = p;
p = q;
}
length ++;
}
T pop()//出棧并且將出棧的元素返回
{
if (length <= 0)
{
abort();
}
Node *q;
int data;
q = p;
data = p->data;
p = p->next;
delete(q);
length --;
return data;
}
int size()//返回元素個(gè)數(shù)
{
return length;
}
T top()//返回棧頂元素
{
return p->data;
}
bool isEmpty()//判斷棧是不是空的
{
if (length == 0)
{
return true;
}
else
{
return false;
}
}
void clear()//清空棧中的所有元素
{
while(length > 0)
{
pop();
}
}
};
int main()
{
Stack<char> s;
s.push('a');
s.push('b');
s.push('c');
while(!s.isEmpty())
{
cout<<s.pop()<<endl;
}
return 0;
}
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
純c語(yǔ)言優(yōu)雅地實(shí)現(xiàn)矩陣運(yùn)算庫(kù)的方法
本文主要介紹了純c語(yǔ)言優(yōu)雅地實(shí)現(xiàn)矩陣運(yùn)算庫(kù),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08
C++ Boost Random隨機(jī)函數(shù)詳解
Boost是為C++語(yǔ)言標(biāo)準(zhǔn)庫(kù)提供擴(kuò)展的一些C++程序庫(kù)的總稱。Boost庫(kù)是一個(gè)可移植、提供源代碼的C++庫(kù),作為標(biāo)準(zhǔn)庫(kù)的后備,是C++標(biāo)準(zhǔn)化進(jìn)程的開發(fā)引擎之一,是為C++語(yǔ)言標(biāo)準(zhǔn)庫(kù)提供擴(kuò)展的一些C++程序庫(kù)的總稱2022-11-11
C/C++實(shí)現(xiàn)圖書信息管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了c/c++實(shí)現(xiàn)圖書信息管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11
基于C++中常見內(nèi)存錯(cuò)誤的總結(jié)
本篇文章是對(duì)C++中常見的內(nèi)存錯(cuò)誤進(jìn)行了總結(jié)介紹。需要的朋友參考下2013-05-05

