詳解C語言數(shù)據(jù)結(jié)構(gòu)之棧
棧的鏈式實現(xiàn)
主要內(nèi)容
(1) 棧包含7個元素,依次是67,3,88,6,1,7,0,采用尾插入法創(chuàng)建 棧,為該棧設(shè)置兩個指針,一個bottom和一個top指針;
(2) 入棧函數(shù)push,該函數(shù)完成向棧中插入元素的功能,利用push函數(shù),將數(shù)字-9插入到棧內(nèi),并將棧里的元素遍歷;
(3) 出棧函數(shù)pop,該函數(shù)完成從棧中刪除元素的功能,利用pop函數(shù),刪除此時棧里面的3個元素,并遍歷棧;
(4) 函數(shù)length,求出此時棧內(nèi)元素的個數(shù)。
代碼實現(xiàn):
#include<stdio.h> #include<stdlib.h> struct node { int date; struct node *next; }; struct stack { struct node *bottom; struct node *top; }s; struct stack *creat(struct stack *s); //創(chuàng)建棧 void push(struct stack *s,int e); //入棧 void print(struct stack *s); //打印輸出 void pop(struct stack *s); //出棧 void length(struct stack *s); //輸出棧的長度 int main() { struct stack *s; int e; s=creat(s); push(s,67); push(s,3); push(s,88); push(s,6); push(s,1); push(s,7); push(s,0); printf("初始棧元素為:"); print(s); printf("\n"); printf("\n"); push(s,-9); printf("插入元素后:"); print(s); printf("\n"); printf("\n"); pop(s); pop(s); pop(s); printf("刪除元素后:"); print(s); printf("\n"); printf("\n"); length(s); return 0; } struct stack *creat(struct stack *s) { s=(struct stack *)malloc(sizeof(struct stack )); s->bottom=s->top=(struct node *)malloc(sizeof(struct node)); s->top->next=NULL; s->bottom->next=NULL; return s; } void push(struct stack *s,int e)//進棧 { struct node *p; p=(struct node *)malloc(sizeof(struct node)); p->date=e; p->next=NULL; s->top->next=p; s->top=p; } void pop(struct stack *s)// 出棧 { struct node *p,*q; p=s->bottom; while(p->next!=NULL) { q=p; p=p->next; } q->next=NULL; s->top=q; } void print(struct stack *s)//打印輸出 { struct node *p = s->bottom->next; while(p!=NULL) { printf("%4d",p->date); p=p->next; } } void length(struct stack *s)//計算長度 { struct node *p=s->bottom->next; int i=0; while(p!=NULL) { i++; p=p->next; } printf("此時棧的長度為:%4d",i); }
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
vscode 配置 C/C++ 編譯環(huán)境的詳細圖文教程
這篇文章主要介紹了vscode 配置 C/C++ 編譯環(huán)境的詳細教程,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05使用C++和Crypto++庫實現(xiàn)AES加密與解密
在這篇博客中,我們將深入探討如何利用C++和Crypto++庫實現(xiàn)高效且安全的AES加密與解密機制,Crypto++是一款高度認可的免費C++類庫,文中通過代碼示例介紹的非常詳細,具有一定的參考價值,需要的朋友可以參考下2024-01-01C++實現(xiàn)LeetCode(202.快樂數(shù))
這篇文章主要介紹了C++實現(xiàn)LeetCode(202.快樂數(shù)),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-08-08