C 實現順序棧和鏈棧

2021-08-25 01:49:07 字數 1318 閱讀 8109

順序棧和鏈棧分別類似於順序表和單鏈表,只是由於棧的first in last out性質,其操作相對簡單,是順序表和單鏈表的子集。

鏈棧中的鏈不使用head屬性,這一屬性是多餘的,使用鏈棧類的topnode屬性即可。另外,為了避免每次返回鏈棧的長度都要遍歷所有結點,在鏈棧類中增加num屬性,push操作時,num自加,pop操作時,num自減,始終等於鏈棧中的結點數。

using system; using system.collections.generic; using system.linq; using system.text; namespace stack //順序棧類 class sequencestack: istackds set } public int toppointer//沒有set,不應該在類外修改top的pointer } public t this[int i]//沒有set,不支援類外修改 } public sequencestack():this(100)//預設maxsize為100 public sequencestack(int size) #region istackds成員 public int getlength() public bool isempty() public void clear() public void push(t t) public t pop() else } public t gettop() else } #endregion } //鏈棧的結點類 class node set } public nodenext set } public node() public node(t t) } //鏈棧類。不設定裡面鍊錶的head屬性,因為這是多餘的。用topnode表示棧頂即可。 //另,為了避免返回長度時對鍊錶遍歷,使用num計數,使num與棧內的結點個數同時變化。 class linkedstack:istackds set } public int num set } public linkedstack() public linkedstack(nodenode) #region istackds成員 public int getlength() public bool isempty() public void clear() public void push(t t) public t pop() else } public t gettop() else } #endregion } class program console.readline(); linkedstackstack2 = new linkedstack(); stack2.push(3); stack2.push(9); while (!stack2.isempty()) console.readline(); } } }

C 實現順序棧和鏈棧

二,順序棧的實現 三,鏈棧的實現 棧的初始化 template typename t bool stack isempty 判斷棧是否為空 template typename t int stack getlength 獲得棧中資料元素的個數 template typename t int stac...

順序棧和鏈棧實現

以前參照weiss的 資料結構與演算法分析 寫過兩篇隨筆 因為考研的緣故,現在看了嚴蔚敏的 資料結構 c版 也跟著寫了一遍,原理都類似 鏈棧 鏈棧 typedef status typedef struct node stack typedef struct node ptrtonode struc...

棧的實現 順序棧和鏈棧

本文主要給出我對棧的實現,包括順序棧和鏈棧兩種實現方式。common.h ifndef common h define common h 函式結果狀態碼 define true 1 define false 0 define ok 1 define error 0 define infeasible...