/*
============================================================================
Name : 堆栈(堆栈,堆栈,堆中开的栈空间,所以叫堆栈)
Author : Swair Fang
Version : 1.1
Copyright : by Swair Fang
Description : 堆栈实现, Ansi-style
功能:
1.初始化堆栈
2.压栈
3.出栈
4.查看栈顶
5.清空一个栈
6.打印栈
============================================================================
*/
#include
#include
#ifndef _Stack_H
#define _Stack_H
typedef int ElementType;
//构建节点
typedef struct Node
{
ElementType Element;
struct Node *Next;
} *Stack,*Position;
//1.初始化一个堆栈
Stack Create()
{
Stack S=(Stack)malloc(sizeof(struct Node));
if(S==NULL)
printf("Out of space!!!");
S->Next=NULL;
return S;
}
//2.压栈
void Push(Stack S,ElementType X)
{
Position TmpCell=(Position)malloc(sizeof(struct Node));
if(TmpCell==NULL)
{
printf("Out of space!!!");
exit(1);
}
TmpCell->Element=X;
TmpCell->Next=S->Next;
S->Next=TmpCell;
}
//3.出栈
ElementType Pop(Stack S)
{
if(S==NULL||S->Next==NULL)
printf("Empty stack");
else
{
Position FirstCell=S->Next;
S->Next=S->Next->Next;
ElementType X=FirstCell->Element;
free(FirstCell);
return X;
}
}
//4.查看栈顶
ElementType Top(Stack S)
{
if(S==NULL||S->Next==NULL)
printf("Empty stack");
else
{
return S->Next->Element;
}
}
//5.清空一个栈
void MakeEmpty(Stack S)
{
if(S==NULL)
printf("Must use CreateStack first");
else
{
Position P,Tmp;
P=S->Next;
S->Next=NULL;
while(P!=NULL)
{
Tmp=P->Next;
free(P);
P=Tmp;
}
}
}
//6.打印栈
void PrintStack(Stack S)
{
if(S->Next==NULL)
printf("链表为空\n");
else
{
Position P=S->Next;
while(P!=NULL)
{
char *cp=(char*)P;
printf("0x%x: %d\n ",cp,P->Element);
P=P->Next;
}
printf("\n");
}
}
#endif/*_Stack_H*/
int main()
{
Stack S=Create();
printf("将1-10依次压栈\n");
int i=0;
while(i++<10)
Push(S,i);
PrintStack(S);
printf("出栈第1次后\n");
Pop(S);
printf("出栈第2次后\n");
Pop(S);
PrintStack(S);
MakeEmpty(S);
exit(0);
}
C堆栈实现
最新推荐文章于 2024-07-03 20:18:23 发布