체인 스 택 의 실현

체인 스 택, 핵심 사상 은 링크 의 머리 에 삽입 하고 삭제 하 는 것 이다.
/*  Author : Moyiii
 *  Mail:  [email protected]
 *        
 *        ,         ,    。
 *      BUG,        ,      
*/
#include <iostream>

using namespace std;

class Node
{
public:
    char data;
    Node *next;
};

class LinkStack
{
public:
    LinkStack();
    ~LinkStack();
    void push(const char x);
    void pop();
    void getTop(char &x);
    void clear();
    bool isEmpty();
    int getLength();
    void print();
private:
    Node *head;
    int length;
};

LinkStack :: LinkStack()
{
    head = new Node;
    head->next = NULL;
}

//          ,         
void LinkStack :: push(const char x)
{
    Node *node = new Node;
    if(!node)
    {
        cout << "Malloc ERROR" << endl;
        return;
    }

    node->data = x;
    node->next = head->next;
    head->next = node;
    length++;
    return;
}

void LinkStack :: pop()
{
    if(head->next == NULL)
    {
        cout << "No elems,pop error!" << endl;
        return;
    }

    Node *p = head->next;
    head->next = p->next;
    delete p;
    length--;
    return;
}

void LinkStack :: getTop(char &x)
{
    if(head->next == NULL)
    {
        cout << "No elems,Top error!" << endl;
        return;
    }
    x = head->next->data;
    return;
}

void LinkStack :: clear()
{
    while(head->next != NULL)
    {
        Node *p = head->next;
        head->next = p->next;
        delete p;
    }
    length = 0;
    return;
}

bool LinkStack :: isEmpty()
{
    return (NULL == head->next);
}

//    length   ,        
int LinkStack :: getLength()
{
    return length;
}

void LinkStack :: print()
{
    cout << "------The Stack is:------" << endl;
    Node *p = head->next;
    while( NULL != p )
    {
        cout << "| " << p->data << " |" ;
        if(p == head->next)
        {
            cout << "←TOP";
        }
        cout << endl;
        p = p->next;
    }
    return;
}

LinkStack :: ~LinkStack()
{
    clear();
    delete head;
}

int main()
{
    LinkStack s;
    for(int i = 0; i < 10; ++i)
    {
        s.push(i+'A');
    }
    s.print();
    for(int i = 1; i <= 5; ++i)
    {
        s.pop();
    }
    s.print();
    return 0;
}

좋은 웹페이지 즐겨찾기