/*******链栈*****/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct StackNode/*结点类型*/
{
int data;
struct StackNode *next;
}StackNode,*LinkStackPtr;
typedef struct /***链栈结构*/
{
LinkStackPtr top;
int count;
}LinkStack;
void InitStack(LinkStack *S)/***链栈初始化**/
{
S->top=(LinkStackPtr)malloc(sizeof(StackNode));
if(!(S->top))
{
printf("Error");
return;
}
S->top=NULL;
S->count=0;
return;
}
int StackEmpty(LinkStack S)/*链栈判空*/
{
if(0==S.count)
return 1;
else
return 0;
}
void PUSH(LinkStack *S,int e)/**进栈**/
{
LinkStackPtr p;
p=(LinkStackPtr)malloc(sizeof(StackNode)) ;
p->data=e;
p->next=S->top;
S->top=p;
S->count++;
return;
}
void POP(LinkStack *S,int *e)/*出栈*/
{
LinkStackPtr p;
if(StackEmpty(*S))
{
printf("Error");
return;
}
p=S->top;
*e=S->top->data;
S->top=S->top->next;
free(p);
S->count--;
return;
}
void PrintStack(LinkStack *S)/**依次打印栈中元素**/
{
LinkStackPtr p;
p=S->top;
while(p) /*it is while not if in this traverse*/
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
return;
}
void ClearStack(LinkStack *S)/**栈置空**/
{
LinkStackPtr p,q;
p=S->top;
while(p)
{
q=p;
p=p->next;
free(q);
}
S->count=0;
return;
}
int main(int argc, char *argv[])
{
LinkStack S;
int i;
int *e;
int flag;
InitStack(&S);
srand(time(NULL));
for(i=0;i<6;i++)
{
PUSH(&S,rand()%100+1);
}
PrintStack(&S);
POP(&S,e);
PrintStack(&S);
ClearStack(&S);
flag=StackEmpty(S);
if(flag)
printf("The stack is empty.\n");
else
printf("The stack is not empty.\n");
return 0;
}
链栈相关
最新推荐文章于 2023-06-18 19:21:01 发布