目录
一、链式栈结构模型
二、链式栈的实现
2.1创建
2.2压栈
2.3出栈
2.4判断栈是否为空
2.5查看栈顶
2.6释放栈
三、应用
链式栈实际上就是基于链表,压栈和弹栈可分别看作头插和头删,链表尾部就是栈底,头指针就是栈顶指针
一、链式栈结构模型
typedef int data_t;typedef struct node{data_t data;struct node *next;
}linkstack,*plinkstack;
二、链式栈的实现
typedef int data_t;typedef struct node{data_t data;struct node *next;
}linkstack,*plinkstack;plinkstack stack_create(void); //创建栈
int stack_push(plinkstack top, data_t value); //压栈
data_t stack_pop(plinkstack top); //出栈
int stack_is_empty(plinkstack top); //判断栈是否为空
data_t stack_see_top(plinkstack top); //查看栈顶
//因为是链式栈,动态开辟,所以不用判断栈是否满
plinkstack stack_free(plinkstack top); //释放栈
2.1创建
plinkstack stack_create(void)
{plinkstack top;//申请空间top = (plinkstack)malloc(sizeof(linkstack));if(top == NULL){printf("stack_creat:malloc space failed!\n");return NULL;}//初始化 top作为头指针top->data = 0;top->next = NULL;return top;
}
2.2压栈
int stack_push(plinkstack top, data_t value)
{plinkstack new;//参数检查if(top == NULL){printf("stack_push:linkstack passed is NULL!\n");return -1;}//申请空间+初始化new = (plinkstack)malloc(sizeof(linkstack));if(new == NULL){printf("stack_push:malloc space failed!\n");return -1;}new->data = value;//压栈new->next = top->next;top->next = new;return 1;
}
2.3出栈
data_t stack_pop(plinkstack top)
{plinkstack delete;//待出栈的结点data_t value;//参数检查if(top == NULL){printf("stack_pop:linkstack passed is NULL!\n");return -1;}//更新指向delete = top->next;//栈顶指针指向的结点先出栈top->next = delete->next;//栈顶指针指向出栈的下一个//保存出栈的数据value = delete->data;//释放结点空间free(delete);delete = NULL;return value;
}
2.4判断栈是否为空
int stack_is_empty(plinkstack top)
{//参数检查if(top == NULL){printf("stack_is_empty:linkstack passed is NULL!\n");return -1;} //判断栈顶指针指向的空间是否为空即可return (top->next == NULL? 1 : 0);
}
2.5查看栈顶
data_t stack_see_top(plinkstack top)
{//参数检查if(top == NULL){printf("stack_see_top:linkstack passed is NULL!\n");return -1;}return (top->next->data);
}
2.6释放栈
plinkstack stack_free(plinkstack top)
{plinkstack WaitaToFree;//参数检查if(top == NULL){printf("stack_free:linkstack passed is NULL!\n");return NULL;}//遍历释放即可while(top != NULL){WaitaToFree = top;top = top->next;free(WaitaToFree);}return NULL; //返回给主程序中的指针 避免野指针
}
三、应用
#include <stdio.h>
#include "linkstack.h"int main(void)
{plinkstack s;s = stack_create();if(s == NULL){return -1;}stack_push(s,10);stack_push(s,20);stack_push(s,30);stack_push(s,40);stack_push(s,50);stack_push(s,60);while(!stack_is_empty(s)){printf("pop:%d\n",stack_pop(s));}s = stack_free(s);return 0;
}