用链表实现栈

来源:互联网 发布:php class w3c 编辑:程序博客网 时间:2024/06/05 16:45

用一般链表创建的逆向思维就可以。一般链表创建是新建一个节点作为已有节点的后续节点,而这里是新建一个节点作为已有节点的前驱节点。所以最新创建的节点在链表开头,即栈顶位置。

注意Push、Pop和DeleteStack都会改变栈顶指针,所以必须传引用

StackByList.h

#ifndef _STACK_Htypedef struct StackByList* PtrStackByList;typedef struct StackByList* TopOfStackByList;void Push(int X, TopOfStackByList &S);int Pop(TopOfStackByList &S);int Top(TopOfStackByList S);bool IsEmpty(TopOfStackByList S);void DeleteStack(TopOfStackByList &S);#endifstruct StackByList{int m_value;PtrStackByList m_next;};

StackByList.cpp

#include "StdAfx.h"#include "StackByList.h"void Push(int X, TopOfStackByList &S){PtrStackByList P = NULL;P = new StackByList();P->m_value = X;P->m_next = S;S = P;}int Pop(TopOfStackByList &S){if (S == NULL)throw "Empty stack!";int top = 0;top = S->m_value;PtrStackByList P = S->m_next;delete S;S = P;return top;}int Top(TopOfStackByList S){if (S == NULL)throw "Empty stack!";return S->m_value;}bool IsEmpty(TopOfStackByList S){if (S == NULL)return true;elsereturn false;}void DeleteStack(TopOfStackByList &S){while (S)Pop(S);}

0 0
原创粉丝点击