棧,有兩種實(shí)現(xiàn)方式,一是靜態(tài)的,由數(shù)組實(shí)現(xiàn),一種是動(dòng)態(tài)的,由鏈表實(shí)現(xiàn),只不過它只能從一端進(jìn)出,也就是先進(jìn)后出,很多人喜歡用彈夾舉例,確實(shí),棧和彈夾在很是相似,數(shù)據(jù)就好比彈夾里面的子彈。所以,棧寫起來和鏈表會有那么一點(diǎn)相似。話不多說,直接上代碼。
這里主要羅列出來了棧的創(chuàng)建,添加元素,刪除元素,清空棧,打印棧這幾種基本功能,實(shí)現(xiàn)語言為C語言,里面的測試數(shù)據(jù)可以任意更換。
#include<stdio.h>#include<stdlib.h>#include<malloc.h>//定義一個(gè)節(jié)點(diǎn) typedef struct node{ int age; char*name; struct node* next;}NODE,*PNODE;//定義一個(gè)棧 typedef struct stack{ PNODE top; PNODE bottom;}STACK,*PSTACK;//定義相關(guān)函數(shù) void Create_Stack(PSTACK s);void Push_Stack(PSTACK S,int val,char*name);int Pop_Stack(PSTACK S);void Traverse_Stack(PSTACK S);void Clear_Stack(PSTACK S);//主函數(shù) int main(){ PSTACK S = (PSTACK)malloc(sizeof(STACK)); Create_Stack(S); Push_Stack(S,25,"Tony"); Push_Stack(S,19,"NKPDQZ"); Push_Stack(S,21,"PHILL"); Push_Stack(S,20,"LEO"); Push_Stack(S,22,"FIZE"); Push_Stack(S,23,"SIMONS"); Push_Stack(S,24,"ZHU"); Pop_Stack(S); Traverse_Stack(S); //在這里可以繼續(xù)調(diào)用其他函數(shù) return 0;} //創(chuàng)建一個(gè)棧 void Create_Stack(PSTACK s){ s->bottom = (PNODE)malloc(sizeof(NODE)); if(s->bottom == NULL) { PRintf("內(nèi)存分配出錯(cuò)"); exit(-1); } else { s->top = s->bottom; s->bottom->next = NULL; s->top->next = NULL; }}//壓棧(入棧) void Push_Stack(PSTACK S,int val,char*name){ PNODE p = (PNODE)malloc(sizeof(NODE)); if(p == NULL) { printf("內(nèi)存分配出錯(cuò)"); exit(-1); } else { p->age = val; p->name = name; p->next = S->top; S->top = p; }}//出棧 int Pop_Stack(PSTACK S){ if(S->top == S->bottom) { return -1; } else { PNODE p = S->top; S->top = S->top->next; free(p); p = NULL; return S->top->age; }}//打印棧中的全部元素 void Traverse_Stack(PSTACK S){ PNODE p = S->top; printf("棧中的元素為:/n"); while(p != S->bottom) { printf("%d/t%s/n",p->age,p->name); p = p->next; }}//清空棧void Clear_Stack(PSTACK S){ if(S->top == S->bottom) { return; } else { PNODE p = NULL; while(S->top != S->bottom) { p = S->top; S->top = S->top->next; free(p); p = NULL; } } return;}參考博客:數(shù)據(jù)結(jié)構(gòu):棧的鏈?zhǔn)綄?shí)現(xiàn)(C語言描述)
新聞熱點(diǎn)
疑難解答