【算法导论】基本数据结构

栈和队列

栈和队列都可以利用简单的数组结构实现,操作方法也很简单,但在算法中却有很多的应用。比如“(“、”)”的匹配,波兰表达式的运算中使用到了栈数据结构,也可以利用栈实现二叉树的遍历。

栈:后进先出

template <typename T>
class stack
{
public:
    stack(int size=0){
        data=new T(size);
        top=0;
    };
    ~stack(){delete[] data};
private:
    int size;
    T* data;
    int top;
public:
    bool stackEmpty();
    void push(T x);
    T pop();
    /* data */
};

bool stack::stackEmpty(){
    if(this->top==0)
        return true;
    else
        return false;
}
void stack::push(T x){
    if(top==size)
        return;
    else{
        this->top=this->top+1;
        data[top+1]=x;
    }
}
T stack::pop(){
    if(stack::stackEmpty())
        return ;
    else{
        this->top=this->top-1;
        return data[this->top+1];
    }
}

队列:先进先出

template <typename T>
class queue
{
public:
    queue(int size=0){
        data=new T(size);
        tail=head=0;
    };
    ~queue(){delete []data};
private:
    int size;
    int head;
    int tail;
    T* data;

    /* data */
public:
    void enQueque(T x);
    T deQueue();
};

void queue::enQueque(T x){
    if(tail==size-1&&head>0){
        data[0]=x;
        tail=0;
    }else(tail>head||head>tail+1){
        data[tail]=x;
        tail=tail+1;
    }
}
T queue::deQueue(){
    if(head==tail)
        return ;
    else{
        if(head=size-1)
            head=0;
        else
            head=head+1;
        return data[head];
    }
}

链表

链表顺序是由各对象的指针决定的。链表有很多种表达方式,如单链接的或双链接的,已排序的或未排序的,循环的或未循环的,有哨兵的或无哨兵的。

template<typename T>
class Node
{
public:
    Node(T value){
        this->value=value;
        this->next=null;
        this->prev=null;
    };
    ~Node(){
        delete next;
        delete prev;
    };

private:
    Node* next;
    Node* prev;
    T value;
};

//没有哨兵的形式
template <typename T>
class List
{
public:
    List(Node* head=null){
        this->head=head;
    };
    ~List(){
        delete head;
    };

    /* data */
private:
    Node* head;

public:
    Node* listSearch(T k);
    void listInsert(Node* k);
    void listDelete(Node* x);
};

Node* List::listSearch(T k){
    Node* cur=this->head;
    while(cur!=null&&cur->value!=k){
        cur=cur->next;
    }
    return cur;
}
void List::listInsert(Node* k){
    k->next=head->next;

    if(head!=null){
        head->prev=x;
    }
    this->head=x;
    x->prev=null;
}
void List::listDelete(Node* x){
    if(x->prev!=null)
        x->prev->next=x->next;
    else
        this->head=x->next;
    
    if(x->next!=null)
        x->next-prev=x->prev;
}
posted @ 2014-03-12 10:42  李书明  阅读(221)  评论(0编辑  收藏  举报