棧的C 單鏈表實現

2021-09-28 07:37:04 字數 3205 閱讀 3217

使用c風格的實現,棧的內部使用單鏈表結構實現。實現介面為:建立表頭、入棧、出棧、反轉、列印、清空

**結構如下:

singlelist.h:資料結構的宣告和定義

main.cpp:測試資料結構:

singlelist.h:

#pragma once

#include#includeusing namespace std;

struct node;

typedef node* pnode;

typedef pnode listhead;

bool isempty(listhead head);

listhead initsinglelist();

bool destroysinglelist(listhead head);

bool push(listhead head,int a);

bool pop(listhead head, int & a);

bool reversesinglelist(listhead* head);

void printsinglelist(listhead head);

void printerror(const char * pmsg)

listhead initsinglelist()

pnode->num = 0;

pnode->next = null;

return pnode;

}bool isempty(listhead head)

else }

bool push(listhead head, int a)

pnode->num = a;

pnode->next = head->next;

head->next = pnode;

printerror("push element to list");

return true;

}bool pop(listhead head, int& a)

pnode ptemp;

ptemp = head->next;

a = ptemp->num;

head->next = head->next->next;

delete ptemp;

ptemp = null;

printerror("pop element");

return true;

}bool reversesinglelist(listhead* head)

destroysinglelist(*head);

*head = psubstitude;

return true;

}void printsinglelist(listhead head)

if (isempty(head))

pnode pnode;

cout << "print singlelist:" << endl;

for (pnode = head->next; pnode != null; pnode = pnode->next)

return;

}bool destroysinglelist(listhead head)

} delete head;

head = null;

return true;

}

main.cpp:

#include"singlelist1.h"

#includeusing namespace std;

int main()

cout << "isempty:" << isempty(list) << endl;

cout《執行結果如下:

is empty

isempty:1

push element to list

1push element to list

push element to list

push element to list

push element to list

push element to list

is not empty

print singlelist:

element:[6]

element:[5]

element:[4]

element:[3]

element:[2]

element:[1]

***************==

push element to list

push element to list

push element to list

push element to list

push element to list

push element to list

is not empty

pop element

is not empty

pop element

is not empty

pop element

is not empty

pop element

is not empty

pop element

is not empty

pop element

is empty

empty list no need pop

1is not empty

print singlelist:

element:[1]

element:[2]

element:[3]

element:[4]

element:[5]

element:[6]

***************==

is not empty

pop element

a:1is not empty

pop element

a:2is not empty

pop element

a:3is not empty

pop element

a:4is not empty

pop element

a:5is not empty

pop element

a:6is empty

empty list no need pop

a:6

單鏈表實現棧

程式設計實現下面的棧頂操作 cpp view plain copy print?class mydata 解析 顯然這裡需要實現棧的3種基本操作,即進棧 出棧以及判空。為了方便起見,使用單鏈表結構實現棧並且使用類的形式來定義站內及其節點。首先是節點類和棧類的具體定義,程式 如下 cpp view p...

單鏈表的c 實現

node類標頭檔案 ifndef node h define node h include include using namespace std class node endif node類cpp include node.h using namespace std 過載 運算子 ostream ...

單鏈表的C 實現

include using namespace std struct node class list void insertlist int adata,int bdata void deletelist int adata void outputlist node gethead void lis...