您的位置:首页 > 理论基础 > 数据结构算法

《数据结构与算法分析》—栈的链表和数组实现(C语言)

2016-03-11 09:54 399 查看
/*
*栈的链表实现
*表头作为栈顶
*/
#include <stdio.h>
#include <stdlib.h>
struct Node
{
ElementType Element;
PtrToNode Next;
};
int IsEmpty(Stack S)
{
return S->Next==NULL;
}
void Push(ElementType X,Stack S)//插入在表头
{
Stack p;
p=(struct Node*)malloc(sizeof(struct Node));
p->Element=X;
p->Next=S->Next;
S->Next=p;
}
ElementType Top(Stack S)//表头为栈顶
{
if(!IsEmpty(S))
return S->Next->Element;
return 0;
}
void Pop(Stack S)
{
PtrToNode p=S->Next;
if(IsEmpty(S))
printf("Empty stack");
else
{
S->Next=p->Next;
free(p);
}
}
void MakeEmpty(Stack S)
{
if(S==NULL)
printf("Must use CreateStack first");
else
while(!IsEmpty(S))
Pop(S);
}
void StackPrint(Stack S)
{
struct Node *P=S->Next;
while(P!=NULL)
{
printf("%3d",P->Element);
P=P->Next;
}
}
int main()
{
Stack S;
S=(struct Node*)malloc(sizeof(struct Node));
S->Next=NULL;
int i=0;
for(i=0;i<5;++i)
{
Push(i,S);
}
StackPrint(S);
printf("\nTop=%3d\n",Top(S));//表头为栈顶

Pop(S);
StackPrint(S);
return 0;
}
/*
*栈的数组实现
*
*/
#include <stdio.h>
#include <stdlib.h>
struct StackArr
{
int Capacity;//容量
int TopOfStack;//数组下标
ElementType *Array;
};
int IsEmpty(Stack S)//检查一个栈是否为空栈
{
return S->TopOfStack==EmptyTOS;
}
int IsFull(Stack S)
{
return S->TopOfStack==S->Capacity-1;
}
void MakeEmpty(Stack S)//创建一个空栈
{
S->TopOfStack=EmptyTOS;
}
void Push(ElementType X,Stack S)
{
if(IsFull(S))
printf("Full stack");
else
S->Array[++S->TopOfStack]=X;
}
ElementType Top(Stack S)
{
if(!IsEmpty(S))
return S->Array[S->TopOfStack];
printf("Empty stack");
return 0;
}
void Pop(Stack S)
{
if(IsEmpty(S))
printf("Empty stack");
else
S->TopOfStack--;
}
ElementType TopAndPop(Stack S)
{
if(!IsEmpty(S))
return S->Array[S->TopOfStack--];
printf("Empty stack");
return 0;
}
Stack CreateStack(int MaxElements)
{
Stack S;
if(MaxElements<MinStackSize)
printf("Stack size if too small");
S=malloc(sizeof(struct StackArr));
if(S==NULL)
printf("Out of space!!!");
S->Array=malloc(sizeof(ElementType)*MaxElements);
if(S->Array==NULL)
printf("Out of space!!!");
S->Capacity=MaxElements;
MakeEmpty(S);

return S;
}
void StackArrPrint(Stack S)
{
int i;
for(i=0;i<S->TopOfStack+1;++i)
{
printf("%3d\n",S->Array[i]);
}
}
int main()
{
Stack S=CreateStack(7);
printf("%d\n",S->Capacity);
printf("%d\n",S->TopOfStack);
int i=0;
for(i=0;i<S->Capacity;++i)
{
Push(i,S);
}
StackArrPrint(S);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 c语言