算法与数据结构【三】——栈的C语言实现

来源:互联网 发布:国内财经媒体排名 知乎 编辑:程序博客网 时间:2024/05/16 05:21

栈,有两种实现方式,一是静态的,由数组实现,一种是动态的,由链表实现,只不过它只能从一端进出,也就是先进后出,很多人喜欢用弹夹举例,确实,栈和弹夹在很是相似,数据就好比弹夹里面的子弹。所以,栈写起来和链表会有那么一点相似。话不多说,直接上代码。

这里主要罗列出来了栈的创建,添加元素,删除元素,清空栈,打印栈这几种基本功能,实现语言为C语言,里面的测试数据可以任意更换。

#include<stdio.h>#include<stdlib.h>#include<malloc.h>//定义一个节点 typedef struct node{int age;char*name;struct node* next;}NODE,*PNODE;//定义一个栈 typedef struct stack{PNODE top;PNODE bottom;}STACK,*PSTACK;//定义相关函数 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);//主函数 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);//在这里可以继续调用其他函数 return 0;} //创建一个栈 void Create_Stack(PSTACK s){s->bottom = (PNODE)malloc(sizeof(NODE));if(s->bottom == NULL){printf("内存分配出错");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("内存分配出错");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;}
参考博客:数据结构:栈的链式实现(C语言描述)


0 0