基於鍊錶的模板棧

2021-10-09 11:14:07 字數 1189 閱讀 9722

首先建立乙個結構體模板,即乙個鍊錶節點,作為棧的單元。

template

<

class

t>

struct linkedlist

};

然後新建乙個類,該類有兩個成員,分別為棧頂指標top和棧的大小size,top永遠指向鍊錶的頭部,由於棧只能操作棧頂元素,故新的節點可插入到鍊錶的頭部;該類實現了push、pop、empty、getsize四個方法,具體見**及注釋。

//模板鍊錶棧

template

<

class

t>

class

mystack

//use a new node to store data,and make the node's next point to top,then make the pointer top point to the new node.

void

push

(const t& node)

//make top point to the next node,and return his value.

t pop()

//if top is nullptr,the stack is empty.

bool

empty()

//get the stack's size.

intgetsize()

private

: linkedlist

* top;

int size;

};

使用整形和字串測試正確性以及通用性。

第一篇部落格,水平和語言表達能力有限,勿噴。

棧的實現(基於鍊錶)

首先定義乙個介面 基於已寫好的鍊錶實現的棧 public inte ce stack定義乙個棧的類,繼承stack介面 基於鍊錶實現棧 author hcc 鍊錶的開頭是棧底,鍊錶的末尾是棧頂 public class linkedstackimplements stack override pub...

類模板 》鍊錶,棧

除了構造和析構以外的所有用到模板名稱的地方都加上型別引數 類模板的選擇性例項化 用到哪個函式例項化哪個函式 include template 1 定義乙個型別 2 宣告型別 class clink templateclass node private t mdata node pnext templ...

C語言基於鍊錶的棧

學習資料結構與演算法時實現的棧,參考書目 資料結構與演算法分析 c語言描述 以及在後面會分析我遇到的乙個問題。標頭檔案 stack.h 功能 基於鍊錶的棧,棧頂在表頭 ifndef stack header h define stack header h typedef struct node pn...