詳解C語言數(shù)據(jù)結構之棧
棧的鏈式實現(xiàn)
主要內(nèi)容
(1) 棧包含7個元素,依次是67,3,88,6,1,7,0,采用尾插入法創(chuàng)建 棧,為該棧設置兩個指針,一個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);
}
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內(nèi)容!
相關文章
C語言驅(qū)動開發(fā)之內(nèi)核使用IO/DPC定時器詳解
本章將繼續(xù)探索驅(qū)動開發(fā)中的基礎部分,定時器在內(nèi)核中同樣很常用,在內(nèi)核中定時器可以使用兩種,即IO定時器,以及DPC定時器,感興趣的可以了解一下2023-04-04
C++實現(xiàn)簡單BP神經(jīng)網(wǎng)絡
這篇文章主要為大家詳細介紹了C++實現(xiàn)簡單BP神經(jīng)網(wǎng)絡,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-05-05
Ubuntu 20.04 下安裝配置 VScode 的 C/C++ 開發(fā)環(huán)境(圖文教程)
這篇文章主要介紹了Ubuntu 20.04 下安裝配置 VScode 的 C/C++ 開發(fā)環(huán)境,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05

