本文主要給出我對棧的實現,包括順序棧和鏈棧兩種實現方式。
common.h
#ifndef common_h
#define common_h
/* 函式結果狀態碼 */
#define true 1
#define false 0
#define ok 1
#define error 0
#define infeasible -1
//#define overflow -2
//#define underflow -3
/* 型別定義 */
typedef int status; // status是函式的型別,其值是函式結果狀態碼
typedef int elemtype; // elemtype是資料型別
#endif
seqstack.h
#ifndef seqstack_h
#define seqstack_h
#define stacksize 1024
#include
#include "common.h"
// 順序棧儲存結構宣告
struct seqstack
};// 順序棧基本操作
status push( seqstack& stk, elemtype x );
status pop( seqstack& stk );
elemtype top( seqstack& stk );
bool empty( seqstack& stk );
#endif
status push( seqstack& stk, elemtype x )
stk.data[stk.top++] = x
; return ok;
}
status pop( seqstack& stk )
stk.top--;
return ok;
}
elemtype top( seqstack& stk )
return stk.data
[stk.top-1];
}
bool empty( seqstack& stk )
linkedstack.h
#ifndef linkedstack_h
#define linkedstack_h
#include "common.h"
#include
/* 鏈棧節點宣告 */
struct
listnode
listnode( elemtype x ) : data
(x), next(null)
{}};
typedef
listnode* linkedstack; // linkedstack是指向listnode型別的指標
// 鏈棧基本操作
status push( linkedstack& top, elemtype x );
status pop( linkedstack& top );
elemtype top( linkedstack& top );
bool empty( linkedstack& top );
#endif
注意一定,鏈棧在實現的時候,本質是靠乙個頭指標,也就是top指標。該指標相當於頭指標的作用,出棧入棧都是圍繞該指標進行。
status push( linkedstack& top, elemtype x )
if(!top) top = cur;
else
return ok;
}
status pop( linkedstack& top )
linkedstack nex = top->next;
delete top;
top = nex;
return ok;
}
elemtype top( linkedstack& top )
return top->
data;
}
bool empty( linkedstack& top )
順序棧和鏈棧實現
以前參照weiss的 資料結構與演算法分析 寫過兩篇隨筆 因為考研的緣故,現在看了嚴蔚敏的 資料結構 c版 也跟著寫了一遍,原理都類似 鏈棧 鏈棧 typedef status typedef struct node stack typedef struct node ptrtonode struc...
順序棧和鏈棧的實現
這學期開了資料結構,剛開始以為 應該會很簡單,但是真正實現起來才發現有好多細節需要注意,而且發現指標的姿勢忘了好多好多 130h.h 1 include 2 define max 100 3struct node14 9struct node210 1415 void menu 16bool ini...
棧 實現鏈棧和順序棧)
按不同的儲存結構,可以將棧分為順序棧和鏈棧。順序棧的實現 typedef int datatype const int maxnum 1000 struct sqstack 判斷棧空 bool isempty else return false 判斷棧滿 bool isfull else retur...