#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int ElemType;
typedef struct SNode
{
ElemType data;
struct SNode *next;
}SNode,*LinkStack;
SNode *InitStack();
void DestroyStack(LinkStack SS);
int Push(LinkStack SS,ElemType *ee);
int Pop(LinkStack SS,ElemType*ee);
int Length(LinkStack SS);
void Clear(LinkStack SS);
int IsEmpty(LinkStack SS);
void PrintStack(LinkStack SS);
int GetTop(LinkStack SS,ElemType *ee);
int main()
{
LinkStack SS;
SS=InitStack();
printf("栈的长度是%d\n",Length(SS));
ElemType ee;
ee=1;
Push(SS,&ee);ee=2; Push(SS, &ee);
ee=3; Push(SS, &ee);
ee=4; Push(SS, &ee);
ee=5; Push(SS, &ee);
ee=6; Push(SS, &ee);
ee=7; Push(SS, &ee);
ee=8; Push(SS, &ee);
ee=9; Push(SS, &ee);
ee=10; Push(SS, &ee);
printf("栈的长度是%d\n",Length(SS));
if (GetTop(SS,&ee)==1) printf("栈顶的元素值为%d\n",ee);
PrintStack(SS);
if (Pop(SS,&ee)==1) printf("出栈的元素值为%d\n",ee);
if (Pop(SS,&ee)==1) printf("出栈的元素值为%d\n",ee);
if (Pop(SS,&ee)==1) printf("出栈的元素值为%d\n",ee);
if (Pop(SS,&ee)==1) printf("出栈的元素值为%d\n",ee);
if (Pop(SS,&ee)==1) printf("出栈的元素值为%d\n",ee);
if (Pop(SS,&ee)==1) printf("出栈的元素值为%d\n",ee);
if (Pop(SS,&ee)==1) printf("出栈的元素值为%d\n",ee);
if (Pop(SS,&ee)==1) printf("出栈的元素值为%d\n",ee);
if (Pop(SS,&ee)==1) printf("出栈的元素值为%d\n",ee);
if (Pop(SS,&ee)==1) printf("出栈的元素值为%d\n",ee);
if (Pop(SS,&ee)==1) printf("出栈的元素值为%d\n",ee);
if (Pop(SS,&ee)==1) printf("出栈的元素值为%d\n",ee);
// 销毁链栈SS。
DestroyStack(SS); SS=NULL; // 销毁链栈后把SS置为空,防止野指针。
return 0;
}
SNode *InitStack()
{
SNode *head=(SNode*)malloc(sizeof(SNode));
if(head==NULL)
return NULL;
head->next=NULL;
return head;
}
void Clear(LinkStack SS)
{
if(SS==NULL)
{
return;
}
SNode*tmp1;
SNode *tmp2;
tmp2=SS->next;
while(tmp2!=NULL)
{
tmp1=tmp2->next;
free(tmp2);
tmp2=tmp1;
}
SS->next=NULL;
}
int Length(LinkStack SS)
{
if(SS==NULL) return -1;
int kk=0;
SNode *tmp=SS->next;
while(tmp!=NULL)
{
kk++;
tmp=tmp->next;
}
return kk;
}
void DestroyStack(LinkStack SS)
{
if(SS==NULL)
{
return;
}
SNode*tmp;
while(SS!=NULL)
{
tmp=SS->next;
free(SS);
SS=tmp;
}
SS=NULL;
}
int IsEmpty (LinkStack SS)
{
if(SS==NULL) return -1;
if(SS->next==NULL) return 1;
return 0;
}
void PrintStack (LinkStack SS)
{
if(SS==NULL)
{
return;
}
if(SS->next==NULL)
{
printf("栈为空\n");
return;
}
SNode*tmp=SS->next;
while(tmp!=NULL)
{
printf("%d\n",tmp->data);
tmp=tmp->next;
}
}
int Pop(LinkStack SS,ElemType *ee)
{
if(SS==NULL||ee==NULL)
{
return -1;
}
if(SS->next==NULL)
{
return 0;
}
SNode *tmp=SS->next;
memcpy(ee,&tmp->data,sizeof(ElemType));
SS->next=tmp->next;
free(tmp);
tmp=NULL;
return 1;
}
int GetTop(LinkStack SS, ElemType *ee)
{
if ( (SS == NULL) || (ee == NULL) ) return 0; // 检查空指针。
if (SS->next == NULL) { printf("栈为空。\n"); return 0; }
memcpy(ee,&SS->next->data,sizeof(ElemType));
return 1;
}
int Push(LinkStack SS,ElemType *ee)
{
if((SS==NULL)||(ee==NULL))
return -1;
SNode *tmp=(SNode*)malloc(sizeof(SNode));
if(tmp==NULL) return 0;
memcpy(&tmp->data,ee,sizeof(ElemType));
tmp->next=SS->next;
SS->next=tmp;
return 1;
}
数据结构 链栈
最新推荐文章于 2024-06-11 19:36:10 发布