链式栈
简单实现链式栈
顺序栈是对顺序表的一端操作,那么链式栈则是对链表的一端操作
要达到后进先出这个条件,用链表头插法,再用链表头删法比较容易实现,头插法进栈要考虑栈是否满了,头删法出栈要考虑栈是否为空
代码
config.h
#ifndef _CONFIG_H
#define _CONFIG_H
typedef int Data_t;
struct Node
{
Data_t data;
struct Node *next;
};
typedef struct
{
struct Node *node;
int top;
int size;
}LinkStack;
LinkStack *stack_init(int len);
int stack_ifFul(LinkStack *lstack);
int stack_push(LinkStack *lstack, Data_t value);
int stack_ifEmpty(LinkStack *lstack);
Data_t stack_pop(LinkStack *lstack);
int stack_free(LinkStack *lstack);
#endif
linkStack.c
#include <stdlib.h>
#include <string.h>
#include "config.h"
LinkStack *stack_init(int len)
{
LinkStack *lstack = (LinkStack *)malloc(sizeof(LinkStack));
if(lstack == NULL)
{
return NULL;
}
lstack->top = 0;
lstack->size = len;
lstack->node = NULL;
return lstack;
}
int stack_isFul(LinkStack *lstack)
{
if(lstack->top == lstack->size)
{
return 1;
}
return 0;
}
int stack_push(LinkStack *lstack, Data_t value)
{
if(stack_isFul(lstack))
{
return 0;
}
struct Node *new = (struct Node *)malloc(sizeof(struct Node));
if(new == NULL)
{
free(lstack);
return 0;
}
memset(new, 0, sizeof(struct Node));
new->data = value;
new->next = lstack->node;
lstack->node = new;
lstack->top ++;
return 1;
}
int stack_ifEmpty(LinkStack *lstack)
{
if(lstack->top == 0 || lstack == NULL)
{
return 1;
}
return 0;
}
Data_t stack_pop(LinkStack *lstack)
{
Data_t tmpData;
struct Node *tmpNode = NULL;
if(stack_ifEmpty(lstack))
{
return 0;
}
tmpNode = lstack->node;
tmpData = lstack->node->data;
lstack->node = tmpNode->next;
free(tmpNode);
lstack->top --;
return tmpData;
}
int stack_free(LinkStack *lstack)
{
struct Node *tmpNode = NULL;
while(lstack->node != NULL)
{
tmpNode = lstack->node;
lstack->node = tmpNode->next;
free(tmpNode);
}
lstack->node = NULL;
free(lstack);
lstack = NULL;
return 1;
}
mainPro.c
#include <stdio.h>
#include "config.h"
int main()
{
LinkStack *lstack = stack_init(10);
if(lstack == NULL)
{
return -1;
}
stack_push(lstack, 10);
stack_push(lstack, 20);
stack_push(lstack, 30);
stack_push(lstack, 40);
stack_push(lstack, 50);
/*while(!stack_ifEmpty(lstack))
{
printf("%d\t", stack_pop(lstack));
}
putchar('\n');
*/
if(stack_free(lstack))
{
printf("free done!\n");
}
return 0;
}