資料結構 鏈式堆疊
阿新 • • 發佈:2018-12-14
堆疊分為順序儲存 和 鏈式儲存 兩種
下面給大家提供一個鏈式儲存的,這裡小編是用 C++來描述的堆疊
#include <iostream> using namespace std; typedef struct Node { int data; struct Node * next; }Node; class ChainOfStack { //int top; Node head; void insertAtHead(int data); void deleteAtHead(); public: ChainOfStack(); ~ChainOfStack(); void push(int data); void pop(); int top(); void print(); }; ChainOfStack::ChainOfStack() { head.data = 0; head.next = NULL; } ChainOfStack::~ChainOfStack() { } void ChainOfStack::push(int data) { insertAtHead(data); } void ChainOfStack::insertAtHead(int data) { Node * tmpNode = new Node; tmpNode->data = data; tmpNode->next = head.next; head.next = tmpNode; } void ChainOfStack::pop() { deleteAtHead(); } void ChainOfStack::deleteAtHead() { Node * tmpPtr = head.next; head.next = head.next->next; delete tmpPtr; } int ChainOfStack::top() { return head.data; } void ChainOfStack::print() { Node * p_head = head.next; while (p_head != NULL) { cout << p_head->data << " "; p_head = p_head->next; } cout << endl; } int main(void) { ChainOfStack stack; cout << "入棧:" << endl; for (int i = 0; i < 10; i++) { stack.push(i); stack.print(); } cout << "彈棧:" << endl; for (int i = 0; i < 10; i++) { stack.pop(); stack.print(); } return 0; }