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

初学数据结构之堆栈

2015-07-20 12:48 447 查看
一:数组实现
#define MaxSize 10
typedef struct
{
int Data[MaxSize];
int Top;
}Stack;

void Push(Stack *Ptrs,int item)
{
if(Ptrs->Top==MaxSize-1)
{
printf("堆栈满");
return;
}
else
{
Ptrs->Data[++(Ptrs->Top)]=item;
return;
}
}
int Pop(Stack *Ptrs)
{
if(Ptrs->Top==-1)
{
printf("堆栈空");
return ERROR;
}
else
{
return (Ptrs->Data[(Ptrs->Top)--]);
}
}

二:链表实现
typedef struct Node
{
int Data;
struct Node *Next;
}LinkStack;
LinkStack *Top;

LinkStack *CreateStack()
{
LinkStack *S;
S=(LinkStack *)malloc(sizeof(struct Node));
S->Next=NULLl
return S;
}
int IsEmpty(LinkStack *S)
{
return (S->Next==NULL)
}
void Push(int item,LinkStack *S)
{
struct Node *TmpCell;
TmpCell=malloc(sizeof(struct Node));
TmpCell->Data=item;
TmpCell->Next=S->Next;
S->Next=TmpCell;
}
int Pop(LinkStack *S)
{
struct Node *FirstCell;
int TopElem;
if(IsEmpty(S))
{
printf("堆栈空");
return NULL;
}
else
{
FirstCell=S->Next;
S->Next=FirstCell->Next;
TopElem=FirstCell->Data;
free(FirstCell);
return TopElem;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c 数据结构