怎么在C++中使用鏈表書寫一個棧?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
C++中其實有stack的模板類。功能更為強大。
自己寫一個棧能讓我們對棧這種數據結構更加熟悉。這個棧有一個不足之處就是里面存放的元素類型只能為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()//返回元素個數 { 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()//返回元素個數 { 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; }
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注創(chuàng)新互聯網站建設公司行業(yè)資訊頻道,感謝您對創(chuàng)新互聯建站的支持。
另外有需要云服務器可以了解下創(chuàng)新互聯建站chinadenli.net,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、建站服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
分享名稱:怎么在C++中使用鏈表書寫一個棧-創(chuàng)新互聯
當前路徑:http://chinadenli.net/article4/ddiiie.html
成都網站建設公司_創(chuàng)新互聯,為您提供搜索引擎優(yōu)化、網頁設計公司、網站改版、服務器托管、網站營銷、用戶體驗
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯