一、链式栈
1.何为链式栈?
逻辑结构:栈
链接: 顺序栈中有介绍
存储结构:链式存储
链接: 单链表中有介绍

2.链式栈声明(linkstack.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);linkstack stack_free(linkstack s);
3.链式栈基本运算(linkstack.c)
(1)创建栈:stack_create()
linkstack stack_create() { linkstack s; s = (linkstack)malloc(sizeof(listnode)); if (s == NULL) { printf("malloc failed/n"); return NULL; } s->data = 0; s->next = NULL; return s;}
(2)入栈:stack_push(s, value)
int stack_push(linkstack s, data_t value) { linkstack p; if (s == NULL) { printf("s is NULL/n"); return -1; } p = (linkstack)malloc(sizeof(listnode)); if (p == NULL) { printf("malloc failed/n"); return -1; } p->data = value; p->next = s->next; s->next = p; return 0;}
(3)出栈:stack_pop(s)
data_t stack_pop(linkstack s) { linkstack p; data_t t; p = s->next; s->next = p->next; t = p->data; free(p); p =NULL; return t;}
(4)判断栈是否空:stack_empty(s)
int stack_empty(linkstack s) { if (s == NULL) { printf("s is NULL/n"); return -1; } return (s->next == NULL ? 1 : 0);}
(5)返回栈顶值:stack_top(s)
data_t stack_top(linkstack s) { return (s->next->data);}
(6)销毁栈:stack_free(s)
linkstack stack_free(linkstack s) { linkstack p; if (s == NULL) { printf("s is NULL/n"); return NULL; } while (s != NULL) { p = s; s = s->next; printf("free:%d/n", p->data); free(p); } return NULL;}
4.测试函数(test.c)
#include <stdio.h>#include <stdlib.h>#include "linkstack.h"int main(int argc, const char *argv[]){ linkstack 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);#if 0 while (!stack_empty(s)) { printf("pop:%d/n", stack_pop(s)); }#endif s = stack_free(s); return 0;}