棧的兩種C 實現

2021-06-21 09:40:15 字數 1257 閱讀 4389

棧(stack)是限制插入和刪除只能在乙個位置上進行的表,該位置是表的末端,叫做棧的頂(top),它是後進先出(lifo)的。對棧的基本操作只有push(進棧)和pop(出棧)兩種,前者相當於插入,後者相當於刪除最後的元素。

棧本質上是一種受限制的表,所以可以使用任何一種表的形式來實現它,最常用的是使用鍊錶和陣列。

使用鍊錶的特點:不需要指定其大小,不會浪費空間;進棧和出棧涉及到動態記憶體的申請釋放,時間花銷大;

使用陣列的特點:需要指定其大小,有可能浪費空間,也可能空間不夠用;進棧和出棧不涉及動態記憶體的申請釋放,因此時間上幾乎沒有花銷;另外支援隨機訪問。

結論:一般使用鍊錶是首選,除非滿足兩個條件:1.對執行時的效率要求極高;2.能夠預知棧需要的空間大小。

陣列實現棧:

#include

using namespace std;

class stack

;stack::stack()

bool stack::isempty()

bool stack::isfull()

void stack::push(int n)

else

cout<<"棧溢位"else

cout<<"棧為空"else

cout<<"棧為空"s.push(6);

s.push(8);

s.push(9);

s.push(18);

s.push(88);

s.push(99);

s.gettop();

s.pop();

s.gettop();

s.pop();

s.gettop();

return 0;

}鍊錶實現棧:

#include

using namespace std;

struct node

;class stack

;stack::stack()

void stack:: push(int item)

int stack::pop()

else

q=p->next;

aa=q->data;

p->next=null;

delete q;

q=null;

return aa;

}void stack::display()

coutwhile(head->next)

delete head;

head=null;

}int main()

棧的兩種實現

順序表實現棧 include include 順序表實現棧 define test head printf n s n function define default sz 5 typedef char datatype typedef struct seqstack seqstack 棧的初始化 ...

棧的兩種實現

棧的基本實現 include stdafx.h include include define maxsize 64 using namespace std 基於陣列實現的棧 class stack 預設建構函式 int push int data 元素入棧 int pop 元素出棧 bool ise...

棧的兩種實現方式

一 陣列實現棧 首先需要定義乙個陣列來儲存棧中的資料,並定義乙個變數來記錄陣列中儲存元素的個數,編寫乙個構造方法來構造乙個長度為十得陣列。先頂i有乙個陣列來儲存棧中的元素 private object array 定義陣列中儲存元素的個數 private int size 構造後乙個長度與為10的陣...