栈的链式存储结构

    栈是一种特殊的顺序表,只是从一头进出而已。

 

    下面是一些链栈的基本操作。

 

/* linkstack.h */

#ifndef LINKSTACK_H_INCLUDED
#define LINKSTACK_H_INCLUDED

#include <iostream>
using namespace std;

#define TYPE int

typedef struct _Node {
    TYPE data;
    struct _Node* next;
} Node, *Pnode;

class LinkStack
{
private:
    Pnode base;
    Pnode top;
public:
    LinkStack();
    ~LinkStack();
    bool InitStack();
    void DestroyStack();
    bool ClearStack();
    bool StackEmpty();
    int StackLength();
    bool Pop(TYPE&);
    bool Push(TYPE);
    void StackTraverse();
};

#endif // LINKSTACK_H_INCLUDED
 
/* linkstack.cpp */

#include "linkstack.h"

LinkStack::LinkStack() {
    base = NULL;
    top = NULL;
}

LinkStack::~LinkStack() {
}

bool LinkStack::InitStack() {

    if (base) {
        cout<<"alarm! stack exist"<<endl;
        return false;
    }

    base = new Node;

    if (base) {
        top = base;
        return true;
    }

    return false;
}

void LinkStack::DestroyStack() {

    while (top) {
        Pnode p = top;
        top = top->next;
        delete p;
    }

    base = NULL;
}

bool LinkStack::ClearStack() {

    if (!base) {
        cout<<"alarm! stack not exist"<<endl;
        return false;
    }

    while (top != base) {
        Pnode p = top;
        top = top->next;
        delete p;
    }

    return true;
}

bool LinkStack::StackEmpty() {

    if (!base) {
        cout<<"alarm! stack not exist"<<endl;

    }

    //判断栈为空
    if ((top == base) && (top != NULL)) {
        return true;
    }

    return false;
}

int LinkStack::StackLength() {

    if (!base) {
        cout<<"alarm! stack not exist"<<endl;
        return 0;
    }

    int n = 0;
    Pnode p = top;
    while (p != base) {
        p = p->next;
        n++;
    }

    return n;
}

bool LinkStack::Push(TYPE data) {

    Pnode p = new Node;

    if (p) {
        p->data = data;
        p->next = top;
        top = p;
        return true;
    }

    return false;
}

bool LinkStack::Pop(TYPE &e) {

    if (top==base) {
        cout<<"error! operation fail, do not to Pop(), Maybe the STACK is empty or not exist"<<endl;
        return false;
    }

    e = top->data;

    Pnode p = top;
    top = top->next;

    delete p;
    return true;
}

void LinkStack::StackTraverse() {

    if (!base) {
        cout<<"alarm! stack not exist"<<endl;
        return;
    }

    Pnode p = top;

    while (p!=base) {
        cout<<p->data<<" ";
        p = p->next;
    }

    cout<<endl;
}
 

 

你可能感兴趣的:(存储)