赞
踩
1. 概念
典型的栈结构如下图所示:栈结构只能在一端操作,该操作端叫做栈顶,另一端叫做栈底。栈结构按照“后进先出”(Last In First Out, LIFO)的方式处理结点数据。
图 1 栈结构
栈结构也包括顺序结构与链式结构两种。
在栈结构中只有栈顶元素是可以访问的,因此栈结构的操作也比较简单,主要两个即入栈和出栈。
- 1#include <unistd.h>
- 2#include <string.h>
- 3#include <stdlib.h>
- 4#include <stdio.h>
- 5
- 6#define MAX_SIZE 10
- 7
- 8typedef struct {
- 9 int id;
- 10 char name[64];
- 11 int age;
- 12}Student;
- 13
- 14typedef struct {
- 15 Student info[MAX_SIZE+1]; //数据元素
- 16 int top; //栈顶
- 17}Stack;
- 18
- 19//初始化栈
- 20Stack *stackInit(void)
- 21{
- 22 Stack *stk = (Stack *)malloc(sizeof(Stack));
- 23 if(NULL == stk){
- 24 return NULL;
- 25 }
- 26 stk->top = 0;
- 27 return stk;
- 28}
- 29
- 30//判空栈
- 31int stackIsEmpty(Stack *stk)
- 32{
- 33 return (0 == stk->top);
- 34}
- 35
- 36//判满栈
- 37int StackIsFull(Stack *stk)
- 38{
- 39 return (stk->top >= MAX_SIZE);
- 40}
- 41
- 42//清空栈
- 43int stackClear(Stack *stk)
- 44{
- 45 stk->top = 0;
- 46}
- 47
- 48//释放
- 49void StackFree(Stack *stk)
- 50{
- 51 if (stk)
- 52 free(stk);
- 53}
- 54
- 55//入栈
- 56int stackPush(Stack *stk, Student data)
- 57{
- 58 if (stk->top+1 > MAX_SIZE)
- 59 return -1;
- 60
- 61 stk->info[++stk->top] = data;
- 62
- 63 return 0;
- 64}
- 65
- 66//出栈
- 67int stackPop(Stack *stk, Student *data)
- 68{
- 69 if (stackIsEmpty(stk))
- 70 return -1;
- 71
- 72 *data = stk->info[stk->top--];
- 73 return 0;
- 74}
- 75
- 76//读栈顶元素
- 77int stackPeek(Stack *stk, Student *data)
- 78{
- 79 if (stackIsEmpty(stk)) {
- 80 fprintf(stderr,"%s","stack is Empty\n");
- 81 return -1;
- 82 }
- 83 *data = stk->info[stk->top];
- 84 return 0;
- 85}
- 86
- 87int main()
- 88{
- 89 Student stu[3] = {
- 90 {1, "zhangsan",20},
- 91 {2, "lisi",21},
- 92 {3, "wangwu",19}
- 93 };
- 94 Student data = {0};
- 95
- 96 Stack *stk = stackInit();
- 97 if (NULL == stk) {
- 98 fprintf(stderr,"%s","stackInit faield\n");
- 99 return -1;
- 100
- 101 }
- 102 stackPush(stk, stu[0]);
- 103 stackPush(stk, stu[1]);
- 104 stackPush(stk, stu[2]);
- 105
- 106 if (!stackPeek(stk, &data))
- 107 printf("id=%d\tname=%s\tage=%d\n",data.id,data.name,data.age);
- 108
- 109 if (!stackPop(stk, &data))
- 110 printf("id=%d\tname=%s\tage=%d\n",data.id,data.name,data.age);
- 111
- 112 if (!stackPeek(stk, &data))
- 113 printf("id=%d\tname=%s\tage=%d\n",data.id,data.name,data.age);
- 114
- 115 stackClear(stk);
- 116
- 117 if(stackIsEmpty(stk))
- 118 fprintf(stderr,"%s","stack is Empty\n");
- 119 StackFree(stk);
- 120
- 121 return 0;
- 122}
代码比较简单,主要还是想再复习巩固下数据结构相关概念与知识。希望看到的童鞋,可以自己试着写一下^_^
更多文章,欢迎关注公众号交流~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。