之前说了顺序存储,具体分析,请看栈之栈的顺序存储,现在说用链表的操作:
顺序存储的时候,我用的是游标top_of_index 来控制top角标,那么在单链表中怎么控制栈顶呢,
无非就是一直头插就行了,头插就是在栈顶插入。
那么出栈呢,出栈无非就是还是从头操作,因为头是栈顶嘛,我们直接把这个节点销毁(前提是这个节点分配了内存空间)或者指向第一个节点的下一个节点就ok了。
另外,关于单链表的插入与删除,请看单链表的设计,另外关于一些常见操作与顺序存储插不多可以查看我另外一篇文章。
总之呢,大致设计思想就四个字:从头开始。
话不多说,上代码:
linkstack.h
1 #ifndef _LINKLIST_H_
2 #define _LINKLIST_H_
3
4 //元素类型还是放到这个里面控制
5 typedef int element_type;
6
7 typedef struct _t_link_stack link_stack;
8
9 struct _t_link_stack{
10 link_stack *next;//下一个节点的指针
11 element_type value;
12 };
13
14 link_stack *create_stack();
15 int is_empty(link_stack *t_stack);
16 void destroy_stack(link_stack *t_stack);
17 element_type top_stack(link_stack *t_stack);
18 void pop_stack(link_stack *t_stack);
19 void push_stack(link_stack *t_stack,element_type value);
linkstack.c
#include <stdio.h>
#include <stdlib.h>
#include "linkstack.h"
//创建栈
link_stack *create_stack()
{
link_stack *t_stack = (link_stack*)malloc(sizeof(link_stack));
if(t_stack != NULL) {
t_stack->next = NULL;
t_stack->value = 0;//这个可以代表栈里面的元素个数
}
return t_stack;
}
//判断是否为空
int is_empty(link_stack *t_stack)
{
int res = -1;
if(t_stack != NULL) {
res = (t_stack->next == NULL);
}
return res;
}
//销毁栈
void destroy_stack(link_stack *t_stack)
{
//注意一个问题,栈销毁,能遍历嘛,不能,栈只能在top栈顶操作,所以
if(t_stack != NULL) {
free(t_stack);
}
}
//获得栈顶的元素
element_type top_stack(link_stack *t_stack)
{
//栈顶就是头节点指向的第一个元素嘛
if(t_stack == NULL) {
printf("出错\n");
} else {
return t_stack->next->value;
}
}
void pop_stack(link_stack *t_stack)
{
//这里的出栈,我们就让头节点指向第一个节点的下一个节点
if(t_stack != NULL && !is_empty(t_stack)) {
link_stack *p_first = t_stack->next;
t_stack->next = p_first->next;
free(p_first);
t_stack->value--;
}
}
//插入数据,插入数据记得给数据分配相应的内存空间
void push_stack(link_stack *t_stack,element_type value)
{
link_stack *p_node = (link_stack *)malloc(sizeof(link_stack));
if(t_stack != NULL && p_node != NULL) {
p_node->value = value;
p_node->next = t_stack->next;
t_stack->next = p_node;
t_stack->value++;
}
}
然后来看测试文件:
main.c
#include <stdio.h>
#include <stdlib.h>
#include "linkstack.h"
int main()
{
link_stack *t_stack = create_stack();
printf("栈里面的元素个数%d\n",t_stack->value);
element_type value1 = 1;
element_type value2 = 2;
element_type value3 = 3;
//进栈
push_stack(t_stack,value1);
push_stack(t_stack,value2);
push_stack(t_stack,value3);
printf("插入之后栈的元素个数%d\n",t_stack->value);
//循环出栈
while(!is_empty(t_stack)) {
element_type value = top_stack(t_stack);
printf("%d\n",value);
pop_stack(t_stack);
}
printf("出完栈之后的长度%d\n",t_stack->value);
//销毁栈
destroy_stack(t_stack);
return 0;
}
运行结果: