#ifndef STACK_LINK_
#define STACK_LINK_
#include <stdbool.h>
typedef int ElementType;
typedef struct _stack_link
{
ElementType date;
struct _stack_link *next;
}linkStack;
linkStack* init_link_stack();
bool push(linkStack *stack, int value);//入栈
int pop(linkStack *stack);//出栈
bool display_stack(linkStack *stack);//显示栈内所有元素值
bool isEmpt(linkStack *stack);//判断栈是否为空
int get_stack_length(linkStack *stack);//获取栈中元素的个数
#endif
#include <stdio.h>
#include <stdlib.h>
#include "stack_link.h"
linkStack* init_link_stack()
{
linkStack* head = (linkStack*)malloc(sizeof(linkStack));
if(NULL == head){
perror("malloc failed ...");
return NULL;
}
head->date = 0;
head->next = NULL;
return head;
}
/*
fundction: 用链表的头插法模拟入栈操作
*/
bool push(linkStack *stack, int value)
{
if (NULL == stack) {
perror(" stack hasn't be created ...");
return false;
}
linkStack* node = (linkStack*)malloc(sizeof(linkStack));
if(NULL == node){
perror("malloc failed ...");
return false;
}
node->date = value;
node->next = stack->next;
stack->next = node;
return true;
}
/*
用头删法模拟出栈操作
*/
int pop(linkStack *stack)
{
linkStack *p = NULL;
int item;
if(NULL == stack) {
perror("stack hasn't create");
return -1;
}
if(0 == get_stack_length(stack)) {
perror("stack is empty.");
return -1;
}
if (stack->next) {
p = stack->next;
stack->next = p->next;
item = p->date;
free(p);
}
return item;
}
int get_stack_length(linkStack *stack)
{
int len = 0;
if (NULL == stack) {
perror("stack is NULL");
return -1;
}
linkStack *p = stack->next;
while(p) {
len += 1;
p = p->next;
}
return len;
}
bool isEmpt(linkStack *stack)
{
if ( !stack || stack->next == NULL)
return true;
else
return false;
}
bool display_stack(linkStack *stack)
{
if( NULL == stack) {
perror("stack is null.");
return false;
}
linkStack *p = stack->next;
while(p) {
printf(" ---> %d\n", p->date);
p = p->next;
}
return true;
}
int main()
{
linkStack *stack = init_link_stack();
/* test code */
int i = 0;
for (i = 0; i < 10; i++) {
push(stack, i);
}
display_stack(stack);
printf("stack len is %d \n",get_stack_length(stack));
printf("pop date %d \n", pop(stack));
return;
}