链式栈的搭建
所谓链式栈,就是用链表的方式来实现栈的功能。
- 链表:每个元素包含数据和下一个元素的指针
- 栈:先入后出;相关概念:栈顶、栈底
功能:
- 创建链式栈:
- 进栈:
- 出栈:
- 判断是非为空栈:
- 释放栈空间:
下面为实现的代码:
linkstck.h
typedef int data_t;
typedef struct node{
data_t data;
struct node *next;
}listnode, *linkstack;
linkstack stack_create();
int stack_push(linkstack s, data_t value);
data_t stack_pop(linkstack s);
int stack_empty(linkstack s);
data_t stack_top(linkstack s);
int stack_free(linkstack s);
linkstack.c
#include <stdio.h>
#include <stdlib.h>
#include "linkstack.h"
linkstack stack_create()
{
linkstack s;
s = (linkstack)malloc(sizeof(listnode));
if (s ==NULL)
{
/* code */
printf("malloc failed\n");
return NULL;
}
s->data = 1;
s->next = NULL;
return s;
}
int stack_push(linkstack s, data_t value)
{
linkstack p;
if (s == NULL)
{
/* code */
printf("s is NULL\n");
return -1;
}
p = (linkstack)malloc(sizeof(listnode));
if (p == NULL)
{
/* code */
printf("malloc failed\n");
return -1;
}
p->data = value;
p->next = s->next;
s->next = p;
return 0;
}
data_t stack_pop(linkstack s)
{
linkstack p;
data_t t;
if (s == NULL)
{
/* code */
printf("s is NULL\n");
return -1;
}
p = s->next;
s->next = p->next;
t = p->data;
free(p);
p == NULL;
return t;
}
int stack_empty(linkstack s)
{
if (s == NULL)
{
/* code */
printf("s is NULL\n");
return -1;
}
return (s->next == NULL ? 1 : 0);
}
data_t stack_top(linkstack s)
{
return (s->next->data);
}
int stack_free(linkstack s)
{
linkstack p;
while (s != NULL)
{
/* code */
p = s;
s = s->next;
printf("free : %d\n", p->data);
free(p);
}
printf("s is NULL\n");
return NULL;
}
test.c
#include <stdio.h>
#include <stdlib.h>
#include "linkstack.h"
int main(int argc, char const *argv[])
{
/* code */
linkstack s;
data_t top_value;
s = stack_create();
if (s == NULL)
{
/* code */
return -1;
}
else{
printf("linkstack create successful\n");
}
stack_push(s, 10);
stack_push(s, 20);
stack_push(s, 30);
stack_push(s, 40);
top_value = stack_top(s);
printf("topvalue is %d\n", top_value);
while (!stack_empty(s))
{
/* code */
printf("pop:%d\n", stack_pop(s));
}
stack_free(s);
return 0;
}