栈的链式存储实现

来源:互联网 发布:黑帮之地mac 编辑:程序博客网 时间:2024/05/17 04:18
#ifndef _LINK_STACK_LIST_H_#define _LINK_STACK_LIST_H_#pragma once/************************************************************************//*                    栈的链式存储实现LinkStackList                     *//************************************************************************//**栈表链式存储实现*/typedef struct LinkStackListNode{LinkStackListNode* Next;ElemType data;}LinkStackListNode,*LinkStackListNodePtr;typedef struct LinkStackList{LinkStackListNodePtr top;int count;}LinkStackList;/*初始化操作,建立一个空的栈S。*/Status InitStack(LinkStackList* S);/*若栈存在,则销毁它*/Status DestoryStack(LinkStackList* S);/*将栈清空*/Status ClearStack(LinkStackList* S);/*若栈为空返回true,否则返回false*/bool StackEmpty(LinkStackList S);/*若栈不为空,返回栈顶元素*/Status GetTop(LinkStackList S,int* e);/*如果栈存在,插入新元素e到栈S中,并成为新的栈顶元素*/Status Push(LinkStackList* S,int e);/*删除栈S中栈顶元素,并返回这个位置的元素值e*/Status Pop(LinkStackList* S,int *e);/*返回栈S的元素个数*/int StackLength(LinkStackList S);/*遍历栈S元素*/Status TraverseStack(LinkStackList S);#endif//_LINK_STACK_LIST_H_


#include "stdafx.h"#include "LinkStackList.h"/*初始化操作,建立一个空的栈S。*/Status InitStack(LinkStackList* S){LinkStackListNodePtr top =  (LinkStackListNodePtr)malloc(sizeof(LinkStackListNode));top->Next = NULL;S->top = top;S->count = 0;return OK;}/*若栈存在,则销毁它*/Status DestoryStack(LinkStackList* S){ClearStack(S);free(S);S = NULL;return OK;}/*将栈清空*/Status ClearStack(LinkStackList* S){if(StackEmpty(*S))return OK;LinkStackListNodePtr top = S->top;while(top->Next){LinkStackListNodePtr delNode = top;S->top = delNode->Next;free(delNode);S->count--;top = S->top;}return OK;}/*若栈为空返回true,否则返回false*/bool StackEmpty(LinkStackList S){return S.count ==0 && S.top->Next == 0;}/*若栈不为空,返回栈顶元素*/Status GetTop(LinkStackList S,int* e){if(StackEmpty(S))return ERROR;*e = S.top->data;return OK;}/*如果栈存在,插入新元素e到栈S中,并成为新的栈顶元素*/Status Push(LinkStackList* S,int e){LinkStackListNodePtr newNode =  (LinkStackListNodePtr)malloc(sizeof(LinkStackListNode));newNode->data = e;newNode->Next = S->top;S->top = newNode;S->count++;return OK;}/*删除栈S中栈顶元素,并返回这个位置的元素值e*/Status Pop(LinkStackList* S,int *e){LinkStackListNodePtr top =  S->top;*e = top->data;S->top = top->Next;free(top);S->count--;return OK;}/*返回栈S的元素个数*/int StackLength(LinkStackList S){return S.count;}/*遍历栈S元素*/Status TraverseStack(LinkStackList S){if(StackEmpty(S))return OK;LinkStackListNodePtr top = S.top;int i = S.count;while(top->Next){std::cout<<"第"<<i--<<"个元素为:"<<top->data<<std::endl;top = top->Next;}return OK;}


0 0
原创粉丝点击