链表栈的代码已经写了好久了,今天给大家分享出来。
链表栈还是链表的那几样操作,很简单,把链表搞定,它就不在话下了。不对它做过多介绍了,直接贴代码,水平有限,有错误还请指出。
lstack.h
#ifndef _STACK_H#define _STACK_H#define MAXSIZE 10typedef struct node{ int data; struct node * next;} Node;typedef struct stack{ Node * top; int size;} Stack;void s_init(Stack * stack);//初始化int s_size(Stack * stack);//栈大小void s_push(Stack * stack, const int data);//入栈void s_pop(Stack * stack);//出栈int s_top(Stack * stack);//栈顶元素bool s_empty(Stack * stack);//为空bool s_full(Stack * stack);//为满void s_destroy(Stack * stack);//销毁#endif //_STACK_H
lstack.c
#include#include #include #include #include #include "lstack.h"static Node* make_node(const int data);//创建节点static void destroy_node(Node * current);//销毁节点void s_init(Stack * stack){ stack->top = make_node(INT_MIN);//创建一个头节点 stack->size = 0;}int s_size(Stack * stack){ return stack->size;}void s_push(Stack * stack, const int data){ Node * node;//新节点指针 assert(stack->size != MAXSIZE); node = make_node(data); node->next = stack->top;//将新节点next指向栈顶 stack->top = node;//将栈顶指向新节点 stack->size++;}void s_pop(Stack * stack){ Node * current;//保存栈顶指针 assert(stack->size != 0); current = stack->top; stack->top = stack->top->next;//栈顶指针下移 destroy_node(current); stack->size--;}int s_top(Stack * stack){ return stack->top->data;}bool s_empty(Stack * stack){ return stack->size == 0;}bool s_full(Stack * stack){ return stack->size == MAXSIZE;}void s_destroy(Stack * stack){ Node * current = stack->top; while (current != NULL)//遍历链表 { destroy_node(current); current = current->next; } stack->size = -1;}static Node* make_node(const int data){ Node * node = (Node *)malloc( sizeof(Node) ); if ( node == NULL ) exit(1); node->data = data; node->next = NULL; return node;}static void destroy_node(Node * current){ assert(current != NULL); free(current);}