链式链的实现

MyStack.h

..............................................................................................................................................................................................

#include<assert.h>
#define NULL 0
class Stack;
class StackNode
{
    friend class Stack;
private:
    int data;
    StackNode *link;
    StackNode(int d=0,StackNode *l=NULL):data(d),link(l){}
   
};

class Stack
{
public:
    Stack(){top=NULL;}
    ~Stack();
    void Push(int item);
    int Pop();
    int GetTop();
    void MakeEmpty();
    int IsEmpty() const{return top==NULL;}
private:
    StackNode *top;
};

Stack::~Stack()
{
    StackNode *p;
    while(top!=NULL)
    {
        p=top;
        top=top->link;
        delete p;
    }
}
void Stack::Push(int item)
{
    //top=new StackNode(item,top);
    StackNode *p=new StackNode();
    p->data=item;
    p->link=top;
    top=p;
}
int Stack::Pop()
{
    assert(!IsEmpty());
    StackNode *p;
    p=top;
    top=top->link;
    int top_value=p->data;
    return top_value;
    delete p;
}
int Stack::GetTop()
{
    assert(!IsEmpty());
    int top_value=top->data;
    return top_value;
}
void Stack::MakeEmpty()
{
    StackNode *p;
    while(top!=NULL)
    {
        p=top;
        top=top->link;
        delete p;
    }
}

..........................................................................................................................................................................................

StaticTest.cpp

#include"MyStack.h"
#include<iostream>

using namespace std;

int main()
{
    Stack stk;
    stk.Push(3);
    stk.Push(5);
    stk.Push(8);
    stk.Push(10);
    stk.Push(99);
    stk.Push(7);
    while(!stk.IsEmpty())
    {
        int value=stk.Pop();
        cout<<"Pop value is: "<<value<<"."<<endl;
    }
    stk.Push(1);
    stk.Push(2);
    stk.Push(3);
    stk.Push(4);
    stk.Pop();
    stk.Pop();
    cout<<"The new top value is:"<<stk.GetTop()<<"."<<endl;

    stk.MakeEmpty();
    if(stk.IsEmpty())
    {
        cout<<"链表为空,呵呵! "<<endl;
    }


    return 0;
}

你可能感兴趣的:(null,delete,Class)