#include <stdio.h>
#include<stdlib.h>
typedef int DataType;
typedef struct Node
{
DataType data;
struct Node* next;
} LStackNode, *LinkStack;
void InitStack(LinkStack* top)
{
if ((*top = (LinkStack)malloc(sizeof(LStackNode))) == NULL)
{
exit(-1);
}
(*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->next;
while(p != NULL)
{
printf("%-3d",p->data);
p=p->next;
}
printf("\n");
}
int main () {
LinkStack Ls;
DataType data;
InitStack(&Ls);
printf("将1,2,3,4依此入栈:\n\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("栈的长度为:%d\n", StackLength(Ls));
printf("栈顶元素为:%d\n", GetTop(Ls, &data));
printf("将9入栈:\n");
PushStack(Ls, 9);
printf("栈的长度为:%d\n", StackLength(Ls));
printf("栈顶元素为:%d\n", GetTop(Ls, &data));
printf("出一次栈!\n");
PopStack(Ls, &data);
printf("栈的长度为:%d\n", StackLength(Ls));
printf("栈顶元素为:%d\n", GetTop(Ls, &data));
StackPrint(Ls);
printf("开始销毁链栈!\n");
DestoryStack(Ls);
printf("链栈销毁结束!\n");
StackPrint(Ls);
StackPrint(Ls);
return 0;
}