棧(鍊錶實現)

2021-08-13 09:30:20 字數 1708 閱讀 3265

1.思路

節點結構體為:乙個int數值,乙個指向下乙個節點的指標struct* next。設定乙個煉表頭節點p,每次入棧的節點都放在p點的下乙個節點,前面的節點則依次往後推移一位;每次出棧時將p->next對應節點值輸出,並將p->next指向p->next->next;當p->next為nullptr則表明棧為空;當p為nullptr,表明棧不存在。

2.**

#include 

using

namespace

std;

struct stack ;

stack* createstack()

bool isempty(stack* p)

return p->next == nullptr;

}stack* pushstack(stack* p, int value)

stack* tmp = (stack*)malloc(sizeof(stack));

tmp->value = value;

tmp->next = p->next;

p->next = tmp;

return p;

}int popstack(stack* p)

stack* tmp = p->next;

p->next = tmp->next;

int res = tmp->value;

free(tmp);

return res;

}void destroy(stack* p)

free(p);

p = nullptr;

}int main()

cout

<< "pop stack until it's empty"

<< endl;

while(!isempty(p))

cout

<< "push 22"

<< endl;

p = pushstack(p, 22);

cout

<< "push 6"

<< endl;

p = pushstack(p, 6);

cout

<< "push 11"

<< endl;

p = pushstack(p, 11);

cout

<< "pop"

<< endl;

cout

<< popstack(p) << endl;

cout

<< "pop"

<< endl;

cout

<< popstack(p) << endl;

cout

<< "push 8"

<< endl;

p = pushstack(p, 8);

cout

<< "pop"

<< endl;

cout

<< popstack(p) << endl;

cout

<< "pop"

<< endl;

cout

<< popstack(p) << endl;

destroy(p);

return

0;}

3.執行結果

鍊錶實現棧

include include typedef int datatype 自定義資料型別,假定為整型 struct node 單鏈表結點型別 typedef struct node pnode 結點指標型別 typedef struct node 單鏈表結點結構 node typedef struc...

鍊錶實現棧

include include typedef int datatype 自定義資料型別,假定為整型 struct node 單鏈表結點型別 typedef struct node pnode 結點指標型別 typedef struct node 單鏈表結點結構 node typedef struc...

用鍊錶實現棧

基於介面實現 public inte ce stack引用到上次已經實現的鍊錶 linkedlistlist new linkedlist 1 獲取棧的長度 獲取棧的長度 return public int getsize 2 判斷棧是否為空 判斷棧是否為空 return public boolea...