最近上來寫了一下棧,理解數據結構的棧。
頭文件:stack.h
初始化棧結構與函數定義:
#include<stdlib.h> #include <stdio.h> #include<memory.h> #define N 100struct stack {int data[N];int top;//標識棧頂 }; typedef struct stack Stack;//Stack別名void init(Stack * p);//初始化 int isempty(Stack * p);//判定棧是否空 int isfull(Stack * p);//判定棧溢出 int gettop(Stack * p);//獲取棧頂 void push(Stack * p, int key);//插入數據 void pop(Stack * p);//吐出 void show(Stack * p);//顯示棧
stack.c
實現函數:初始化,判斷棧頂,溢出等
#include "stack.h"void init(Stack * p)//初始化 {p->top = -1;//代表為空memset(p->data, 0, sizeof(int)*N);//數據清零 } int isempty(Stack * p)//判定棧是否空 {if (p->top==-1){return 1;//1為空 } else{return 0;//0不為空 } } int isfull(Stack * p)//判定棧溢出 {if (p->top==N-1){return 1;///溢出 } else{return 0;//還能再喝點 } } int gettop(Stack * p)//獲取棧頂 {return p->data[p->top];//獲取棧頂 } void push(Stack * p, int key)//插入數據 {if (isfull(p)==1){return;} else{p->top += 1;p->data[p->top] = key;//壓入數據 } } void pop(Stack * p)//吐出 {if (isempty(p)==1){return;} else{p->top -= 1;//出棧 } }void show(Stack * p) {int i;if (isempty(p) == 1){return;}else{printf("\n棧的數據是\n");for (i = 0; i <= p->top;i++){printf("%4d", p->data[i]);//打印棧的數據 }printf("\n");} }
主函數main.c
#include<stdio.h> #include"stack.h" void main() {int i = 0;int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };Stack mystack;init(&mystack);//初始化for (i = 0; i < 10;i++){push(&mystack, i);}//全部裝完再吐while (!isempty(&mystack)){printf("%d", gettop(&mystack)); //獲取棧頂pop(&mystack); //吐出 }printf("\n");//裝一個吐一個。。。。。init(&mystack);//初始化for (i = 0; i < 10; i++){push(&mystack, i);printf("%d", gettop(&mystack));pop(&mystack);}getchar(); }
?