c语言栈的实现以及操作

此文章包含了栈的结构体实现,单数据类型实现,以及清空,判空,入栈,出栈,求栈顶元素的实现

栈作为一个最简单的数据结构,实现起来也非常容易,想想现在有一摞盘子,每次只能取走或放一个盘子且只能最上面进行操作;

那么我们如果有一个索引TOP时刻指向最上面的那个盘子,栈不就实现了么?

第一段是单数据类型的代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxn 110//栈的最大值
typedef int elem;    //方便修改数据类型
typedef struct{
    int top;    ///栈顶的索引
    elem index[maxn];
}Stack;
Stack stack;   ///为了方便这里直接定义全局变量了,用局部变量的话在每个函数加上取地址符和声明就行了
void stack_pop(){   ///元素出栈,此函数无返回值
    stack.top--;
}
void stack_push(elem buf){  ///元素入栈
    stack.index[++stack.top] = buf;
}
int stack_empty(){///判空,如果栈为空的话返回1,否则返回0
    return stack.top == -1;
}
 
void stack_clear(){ ///清空栈
    stack.top = -1;
}
 
int stack_size(){   ///求栈内元素数
    return stack.top+1;
}
elem stack_top(){   ///返回栈顶元素
    return stack.index[stack.top];
}
 
int main()
{
    stack_clear();///初始化栈
    elem buf;
    buf = 10;
    stack_push(buf);
    printf("%d\n",stack_top());
    printf("%d\n",stack_empty());
    printf("%d\n",stack_size());
    stack_pop();
    printf("%d\n",stack_size());
    return 0;
}
下面是结构体栈的实现,和上面的基本一样,只修改了部分代码,添加了一个可以糅合数据类型的结构体数组elem

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxn 11
 
typedef struct {
    int n;
    char str[maxn];
}elem;          ///要存用栈储的数据类型
 
typedef struct{
    int top;    ///栈顶的索引
    elem index[maxn];
}Stack;
Stack stack;   ///为了方便这里直接定义全局变量了,用局部变量的话加上取地址符和声明就行了
void stack_pop(){   ///元素出栈,此函数无返回值
    stack.top--;
}
void stack_push(elem buf){  ///元素入栈
    stack.index[++stack.top].n = buf.n;
    strcpy(stack.index[stack.top].str,buf.str);
}
int stack_empty(){///判空,如果栈为空的话返回1,否则返回0
    return stack.top == -1;
}
 
void stack_clear(){ ///清空栈
    stack.top = -1;
}
 
int stack_size(){   ///求栈内元素数
    return stack.top+1;
}
elem stack_top(){   ///返回栈顶元素
    return stack.index[stack.top];
}
 
int main()
{
    stack_clear();
    elem buf;
    buf.n = 1;
    strcpy(buf.str,"abc");
    stack_push(buf);
    printf("%d  %s\n",stack_top().n,stack_top().str);
    printf("%d\n",stack_empty());
    printf("%d\n",stack_size());
    stack_pop();
    printf("%d\n",stack_size());
    return 0;
}

--------------------- 
作者:bestsort 
来源:CSDN 
原文:https://blog.csdn.net/bestsort/article/details/79682164 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/gb4215287/article/details/86520443