#include "stdlib.h"
#include "stdio.h"
#include "string.h"
/*此代码体现思路*/
typedef unsigned char BOOL;
#define TRUE 1
#define FALSE 0
typedef struct _stackNode
{
int dat;
struct _stackNode* Pre;
}stackNode;
typedef struct _stack
{
stackNode* stack_bottom_ptr;
stackNode* stack_top_ptr;
int stackMaxsize;
int stacklen;
}_stack;
_stack* StackInit(int stackSize)
{
_stack* myStack = (_stack*)malloc(sizeof(_stack));
myStack->stack_bottom_ptr = (stackNode*)malloc(sizeof(stackNode));
myStack->stack_top_ptr = myStack->stack_bottom_ptr;
myStack->stacklen = 0;
myStack->stackMaxsize = stackSize;
return myStack;
}
static BOOL Stack_push(_stack* myStack,int dat)
{
stackNode* temp = NULL;
if( myStack->stacklen >= myStack->stackMaxsize)
{
printf("stack flow! \r\n");
return FALSE;
}
if(myStack->stack_top_ptr == myStack->stack_bottom_ptr && myStack->stacklen < 1) //头结点用来存第一个数据
{
myStack->stack_top_ptr->dat = dat;
}else
{
temp = myStack->stack_top_ptr;
myStack->stack_top_ptr = (stackNode*)malloc(sizeof(stackNode));
myStack->stack_top_ptr->Pre = temp;
myStack->stack_top_ptr->dat = dat;
}
myStack->stacklen ++;
printf(" Stack_push = %d! \r\n",dat);
return TRUE;
}
static int Stack_pop(_stack* myStack)
{
int ret = 0;
stackNode* temp = NULL;
if(!myStack->stacklen)
{
printf("stack empty! \r\n");
return FALSE;
}
if(myStack->stacklen > 1) //保留头结点,不删除
{
ret = myStack->stack_top_ptr->dat;
temp = myStack->stack_top_ptr->Pre;
free( myStack->stack_top_ptr);
myStack->stack_top_ptr = temp;
}
else
ret = myStack->stack_top_ptr->dat;
myStack->stacklen --;
printf(" Stack_pop = %d! \r\n",ret);
return ret;
}
int main()
{
int ret = 0;
_stack* t_stack = StackInit(3);
Stack_push(t_stack,10);
Stack_push(t_stack,20);
Stack_push(t_stack,30);
Stack_push(t_stack,40); //printf("stack flow! \r\n");
ret = Stack_pop(t_stack);
ret = Stack_pop(t_stack);
ret = Stack_pop(t_stack);
ret = Stack_pop(t_stack); //printf("stack empty! \r\n");
return 0;
}
栈的链表方式实现-c语言
最新推荐文章于 2022-09-12 15:37:28 发布