您好,登錄后才能下訂單哦!
怎么在C++中使用鏈表書寫一個棧?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
C++中其實(shí)有stack的模板類。功能更為強(qiáng)大。
自己寫一個棧能讓我們對棧這種數(shù)據(jù)結(jié)構(gòu)更加熟悉。這個棧有一個不足之處就是里面存放的元素類型只能為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()//返回元素個數(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() { //以下為測試代碼 Stack s; s.push(1); s.push(2); s.push(3); while(!s.isEmpty()) { cout<<s.pop()<<endl; } return 0; }
對這段代碼稍加修改,這個棧就能存放其他類型的元素
#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()//返回元素個數(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; }
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。