一、头文件linkstack.h
#ifndef _LINKSTACK_H_
#define _LINKSTACH_H_
#define TRUE 1
#define FALSE 0
//#define NULL 0
typedef int stackData;
typedef struct node{
stackData data;
struct node *next;
}StackNode , *LinkStack;
int InitLinkStack(LinkStack top);
int DestroyLinkStack(LinkStack top);
int LinkStackEmpty(LinkStack top);
int LinkStackLength(LinkStack top);
int GetLinkStackTop(LinkStack top , stackData *element);
int PopLinkStack(LinkStack top , stackData *element);
int PushLinkStack(LinkStack top , stackData element);
int PrintLinkStack(LinkStack top);
#endif
二、实现文件linkstack.c
/**
*说明:栈顶不变,每次进栈数据放在栈顶后面
*/
#include "linkstack.h"
#include <stdio.h>
#include <stdlib.h>
int InitLinkStack(LinkStack top)
{
top->next = NULL;
}
int DestroyLinkStack(LinkStack top)
{
if(LinkStackEmpty(top))
{
free(top);
top = NULL;
return TRUE;
}
StackNode *temp = top;
while(temp->next){
top->next = temp->next->next;
free(temp);
temp = top;
}
free(top);
top = NULL;
}
int LinkStackEmpty(LinkStack top)
{
if(top->next == NULL)
return TRUE;
else
return FALSE;
}
int LinkStackLength(LinkStack top)
{
int count = 0;
if(top->next == NULL)return 0;
StackNode *temp = top;
while(temp->next){
count++;
temp = temp->next;
}
return count;
}
int GetLinkStackTop(LinkStack top , stackData *element)
{
if(LinkStackEmpty(top)){
printf("GetLinkStackTop fail : LinkStackEmpty\n");
return FALSE;
}
*element = top->next->data;
return TRUE;
}
int PushLinkStack(LinkStack top , stackData element)
{
StackNode* temp;
temp = (StackNode*)malloc(sizeof(StackNode));
printf("----------2-------\n");
if(temp == NULL){
printf("PushLinkStack fail : malloc fail\n");
return FALSE;
}
temp->data = element;
temp->next = top->next;
top->next = temp;
return TRUE;
}
int PopLinkStack(LinkStack top , stackData *element)
{
if(LinkStackEmpty(top)){
printf("PopLinkStack fail : LinkStackEmpty\n");
return FALSE;
}
StackNode *temp = top->next;
*element = temp->data;
top->next = temp->next;
free(temp);
return TRUE;
}
int PrintLinkStack(LinkStack top)
{
if(LinkStackEmpty(top)){
printf("PrintLinkStack fail : LinkStackEmpty\n");
return FALSE;
}
StackNode *temp = top;
printf("PrintLinkStack:");
while(temp->next){
printf("%d ",temp->next->data);
temp = temp->next;
}
printf("\n");
return TRUE;
}
int main(int argc ,char *argv[])
{
LinkStack top;
top = (LinkStack)malloc(sizeof(StackNode));
if(!top){
printf("CreateLinkStackInit malloc fail\n");
return -1;
}
InitLinkStack(top);
stackData m = 1;
PushLinkStack(top,m);
PrintLinkStack(top);
}