#include <stdio.h>
#include <stdlib.h>
#include "LinkStack.h"
#include <windows.h>
void InitStack(LinkStack* top)
{
if((*top=(LinkStack)malloc(sizeof(LStackNode)))==NULL)
exit(0);
(*top)->next=NULL;
}
int StackEmpty(LinkStack top)
{
if(top->next==NULL)
return 1;
return 0;
}
void PushStack(LinkStack top,DataType data)
{
LStackNode *p;
p=(LStackNode*)malloc(sizeof(LStackNode));
if(p==NULL)
printf("内存分配失败\n");
else
{
p->data=data;
p->next=top->next;
top->next=p;
}
}
void PopStack(LinkStack top,DataType *data)
{
LStackNode *p;
p=top->next;
if(p==NULL)
printf("栈为空\n");
else
{
top->next=p->next;
*data=p->data;
free(p);
}
}
int GetTop(LinkStack top,DataType*data)
{
LStackNode *p;
p=top->next;
if(StackEmpty(top))
printf("栈为空\n");
else*data=p->data;
return *data;
}
int StackLength(LinkStack top)
{
int count=0;
LStackNode *p;
p=top;
while(p->next!=NULL)
{
count++;
p=p->next;
}
return count;
}
void DestoryStack(LinkStack top)
{
LStackNode *p;
LStackNode *q;
p=top;
while(!p)
{
q=p;
p=p->next;
free(q);
}
}
void StackPrint(LinkStack top)
{
LStackNode*p;
if(StackEmpty(top))
printf("栈为空\n");
printf("栈中元素为\n");
p=top;
while(p->next!=NULL)
{
p=p->next;
printf("%-3d",p->data);
}
printf("\n");
}
#ifndef LINKSTACK_H_INCLUDED
#define LINKSTACK_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
typedef int DataType;
typedef struct Node
{
DataType data;
struct Node*next;
}LStackNode,*LinkStack;
void InitStack(LinkStack* top);
int StackEmpty(LinkStack top);
void PushStack(LinkStack top,DataType data);
void PopStack(LinkStack top,DataType *data);
int GetTop(LinkStack top,DataType*data);
int StackLength(LinkStack top);
void DestoryStack(LinkStack top);
void StackPrint(LinkStack top);
#endif
#include <stdio.h>
#include <stdlib.h>
#include "LinkStack.h"
int main()
{
LinkStack Ls;
DataType data;
InitStack(&Ls);
printf("将1,2,3,4,依次输入栈\n");
PushStack(Ls,1);
PushStack(Ls,2);
PushStack(Ls,3);
PushStack(Ls,4);
StackPrint(Ls);
printf("栈的长度为%d\n",StackLength(Ls));
printf("栈顶元素为%d\n",GetTop(Ls,&data));
printf("\n");
printf("退一次栈\n");
PopStack(Ls,&data);
StackPrint(Ls);
printf("栈的长度为%d\n",StackLength(Ls));
printf("栈顶元素为%d\n",GetTop(Ls,&data));
printf("\n");
printf("将8入栈\n");
PushStack(Ls,8);
printf("将8入栈\n");
PushStack(Ls,8);
printf("退一次栈\n");
PopStack(Ls,&data);
StackPrint(Ls);
DestoryStack(Ls);
return 0;
}