栈的建立和一些基本操作

栈作为一种数据结构,由线性表演变而来,具有后进先出特性,有顺序储存和链式储存两种写法,这里写的是链式储存


#include<stdio.h>

#include<stdlib.h>
typedef int ElementType;


struct Node
{
ElementType Element;

struct Node *Next;
};


typedef struct Node   *PtrToNode;
typedef PtrToNode Stack;


int IsEmpty( Stack S); //判断栈是否为空 
Stack CreatStack(void); //创建空栈 
void MakeEmpty(Stack S); //清空栈 
int Push(ElementType X,Stack S); //入栈 
ElementType Top(Stack S); //栈顶元素 
ElementType Pop(Stack S); //出栈 
int SizeToStack(Stack S); //栈的大小 
void  DestoryStack(Stack *S);


int main(void)
{
Stack S = NULL;

S = CreatStack();

// Push(12,S);
// Push(45,S);
// Push(78,S);
// Push(65,S);

// Pop(S);
// Pop(S);

// MakeEmpty(S);

DestoryStack(&S);


// Push(65,S);

// Pop(S);
printf("%d",IsEmpty(S));

printf("The Top is %d\n",Top(S));

printf("The Size is %d",SizeToStack(S));



return 0;



int IsEmpty( Stack S)
{
if(!S) // 如果S为NULL,表明没有建立栈 
{
printf("Please Creat a Stack First\n");
return 1;
}
else 
return NULL == S->Next ; //如果头指针的Next为NULL 表明栈空 
}




Stack CreatStack(void)
{
Stack S;

S = (Stack) malloc(sizeof(Node));

if(!S)
{
printf("CreatStack Out Of Space\n");
return NULL;
}
else 
{
S->Element = 0; //建立一个空栈,头结点的元素值为栈的大小,返回头结点指针 
S->Next = NULL;
return S;
}
}


void MakeEmpty(Stack S)
{
if(NULL == S) //如果S为NULL,表明栈还没有建立 
{
printf("S is NULL\n");
}
else
{
while( !IsEmpty(S)) //否则清空栈 
{
Pop(S);
}
}

S->Element = 0;
}


int Push(ElementType X,Stack S)
{
Stack P;

if(!S) //如果S为NULL,表明栈还没有建立 
{
printf("Please Creat A Stack\n");
return 0;
}

P = (Stack)malloc(sizeof(struct Node));
P->Next =NULL;
if(!P)
{
printf("Push Out Of Space\n");
}
else 
{
P->Element = X;
  P->Next = S->Next;
S->Next = P;
}

S->Element++;

return 1;
}


ElementType Top(Stack S) //返回栈顶元素 
{
Stack P;
if(!IsEmpty(S))
P = S->Next;
else return 0;

return P->Element;
}




ElementType Pop(Stack S) //出栈 
{
ElementType X = 0;
PtrToNode P;

if(!IsEmpty(S))
{
P = S->Next;
X = P->Element;
S->Next = S->Next->Next;
free(P);
S->Element--;
}
else 
{
printf("Stack Is Empty\n");
}



return X;
}


int SizeToStack(Stack S)
{
if(!S) //如果S为NULL,表明栈还没有建立 
{
printf("Please Creat a Stack First\n");
return 0;
}
else
return S->Element;
}


void  DestoryStack(Stack *S) //销毁栈,传入地址是为了使S等于NULL 
{
PtrToNode P,tmp;

P = *S;
*S = NULL;


while(P->Next)
{
tmp = P;
P = P->Next;
free(tmp);
}

free(P);
}



猜你喜欢

转载自blog.csdn.net/canhelove/article/details/80471785