栈:后进先出;

队列:先进先出

U•ェ•*U不多废话 直接上正文啦

#include <iostream>
using namespace std;
struct Node
{
    int data;
    Node* next;
};
class Stack
{
    private:
        Node* head;
        Node* p;
        int stacklength;
    public:
        Stack()
        {
            head = NULL;
            stacklength = 0;
        }
        void push(int n)//入栈
        {
            Node* q = new Node;
            q->data = n;
            if (head == NULL)
            {
                q->next = head;
                head = q;
                p = q;
            }
            else
            {
                q->next = p;
                p = q;
            }
            stacklength++;
        }
        int top()//返回栈顶元素
        {
            return p->data;
        }
        void pop()//只出栈
        {
            if (stacklength <= 0)
            {
                cout << "栈空" << endl;
                return;
            }
            Node* q;
            q = p;
            p = p->next;
            delete(q);
            stacklength--;
        }
        int size()//返回元素个数
        {
            return stacklength;
        }
        bool isEmpty()//判断栈是不是空的
        {
            if (stacklength == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        void clear()//清空栈中的所有元素
        {
            if (stacklength > 0)
            {
                pop();
            }
        }
    };

 

 

#include<iostream>
using namespace std;
struct QNode   
{
    QNode* next;
    int data; 
};

struct LinkQueue
{
    QNode* front;   
    QNode* rear;   
};
class queue {
public:
    queue() {
        {
            QNode* q;
            q = new QNode;   
            q->next = NULL; 
            this->front = q;
            this->rear = q;
            this->queuelength = 0;
        }
    }
    //        ~queue();
    int IsEmpty() 
        {
            if (this->rear == this->front)
                return 1;
            else
                return 0;
        }
    void EnQueue(int v) {
        QNode* p;  
        p = new QNode;
        p->next = NULL;
        p->data = v;
        this->rear->next = p;
        this->rear = p;   
    }
    int DeQueue() {
        int v;
        QNode* p;
        p = this->front->next;
        v = p->data;
        this->front->next = p->next; 
        if (this->rear == p)   
            this->rear = this->front;
        delete p;
        return v;
    }
    void Display() {
        QNode* p;
        p = this->front->next;
        while (p != NULL) {
            cout << p->data << endl;
            p = p->next;
        }
    }
private:
    QNode* front;     
    QNode* rear;     
    int queuelength;
};
队列

 以上是栈和队列的类。

//对应的题,之后有合适的再来补充。

posted on 2020-01-22 20:09  夜隳·依子  阅读(113)  评论(0编辑  收藏  举报