更新一些堆栈的操作实现

来源:互联网 发布:centos vi 保存退出 编辑:程序博客网 时间:2024/05/21 17:32

堆栈的实现包括有使用指针的实现方式和使用数组的实现方式。

下面为指针的实现方式:

//堆栈也叫做LIFO结构/* 堆栈的基本操作包括清空栈和判断是否是空栈都是栈的操作的一部分 *栈顶是唯一可见的操作 *栈的本质其实也是一个表,任何表的方法都可以用来实现栈 *栈的实现包括两种流行的方法,一种是使用指针来实现,另一种是使用数组来实现*///栈的链表实现//1.使用单链表来实现//首先是定义:#ifdef _Stack_hstruct Nodetypedef struct Node *PtrToNode;typedef ProToNode Stack;intIsEmpty(Stack S);Stack CreatStack(void);voidDisposeStack(Stack S);void MakeEmpty(Stack S);voidPush(ElementType X, Stack S);ElementTypeTop(Stack S)voidPop(Stack S);#endifstruct Node{ElementType Element;PtrToNode Next;};//测试堆栈是否为空int IsEmpty(Stack S){return S->Next == NULL}StackCreatStack(void){Stack S;S = malloc(sizeof(struct Node));if(S == NULL)FatalError("Out of space");S->Next == NULL;MakeEmpty(S)return S;}void//创建一个空的栈 MakeEmpty(Stack S){if(S == NULL)Error("must use CreastStack first");elsewhile(!IsEmpty(S))pop(S);}void//实现压栈的操作Push(ElementType  X,Stack S){PtrToNode TmpCell;TmpCell = malloc(sizeof(struct Node));if(TmpCell == NULL)FatalError("Out of space");else{TmpCell -> ElementType = X;TmpCell -> Next = S->Next;S->Next = TmpCell;}}ElementTypeTop(Stack S){if(!IsEmpty(S))return S->next->Element;Error("Empty Stack");return 0;  //return value is used to avoid waring}voidpop(Stack S){PtrToNode FirstCell;if(IsEmpty(S))Error("Empty Stack");else{FirstCell = S->next;S->Next = S->Next->Next;free(FirstCell);}}

下面是使用数组的实现方式:

#ifdef _Stack_hstruct Stackrecord;struct StackRecord *Stack;int IsEmpty(Stack S);int IsFull(Stack S);Stack CreatStack(int MaxElement);void DisposeStack(Stack S);void MakeEmpty(Stack S);ElementType Top(Stack S);void Pop(Stack S);ElementType TopAndPop(Stack S);#endif /*Stack.h*/Stack CreatStack(int MaxElement){Stack S;if(MaxElement<MinStackSize)Error("Stack is too small");S = malloc(sizeof(struct StackRecord));if(S ==NULL)FatalError("Out of space");S->Array = malloc(sizeof(ElementType)*MaxElement);if(S->Array == NULL)FatualError("Out of space");S->Capacity = MaxElement;MakeEmpty(5);return s;}


0 0
原创粉丝点击