国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

leetcode: Implement Queue using Stacks

2019-11-10 20:06:31
字體:
來源:轉載
供稿:網友

使用satck實現queue

我使用的是 單向鏈表 實現的queue.

考察的是基本的數據結構的實現。

為了實現pop 和push 操作,需要設計兩個指針(我代碼中成了首位兩個節點),一個只想第一個元素,另一個只想最后一個元素,以便快速實現pop和push操作。

結構體Node中的默認構造函數,也算是一個知識點吧。

同一段代碼,中午提交沒通過,晚上一點沒改再次提交竟然通過了。。。。真是沒脾氣。

發現一個問題,pop操作時,如果queue為空,應該返回false.

代碼如下:

class MyQueue {public:    struct Node{        int data;        Node* ptr;        Node(const int x=0,Node* p=NULL):data(x),ptr(p){}    };    /** Initialize your data structure here. */    MyQueue() {        size=0;        head=new Node;        tail=new Node;        head->ptr=tail;        tail->ptr=head;       }       /** Push element x to the back of queue. */    void push(int x) {        if(empty()){            head->ptr=new Node(x,tail);            tail->ptr=head->ptr;        }        else{            tail->ptr->ptr=new Node(x,tail);            tail->ptr=tail->ptr->ptr;        }        ++size;    }       /** Removes the element from in front of queue and returns that element. */    int pop() {        int ret=head->ptr->data;        Node* tmp=head->ptr;        head->ptr=tmp->ptr;        delete tmp;        --size;        return ret;    }       /** Get the front element. */    int peek() {        return head->ptr->data;    }       /** Returns whether the queue is empty. */    bool empty() {        return size==0?true:false;    }   PRivate:    unsigned int size;    Node* head;    Node* tail;};/** * Your MyQueue object will be instantiated and called as such: * MyQueue obj = new MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.peek(); * bool param_4 = obj.empty(); */

修改成指針之后:

class MyQueue{public:    struct Node{        int data;        Node* ptr;        Node(int x=0,Node* p=NULL):data(x),ptr(p){}    };        MyQueue(){        size=0;        head=NULL;        tail=NULL;            }    int pop()    {        if(empty())            return false;        int ret=head->data;        Node* tmp=head->ptr;        delete head;        --size;        head=tmp;        return ret;           }    void push(int x)    {        if(empty())        {            head=new Node(x,nullptr);            tail=head;        }        else        {            tail->ptr=new Node(x,nullptr);            tail=tail->ptr;        }        ++size;    }    int peek()    {        return head->data;    }       bool empty()    {        return size==0?true:false;    }private:    Node* head;    Node* tail;    unsigned int size;    };


上一篇:std::function

下一篇:leetcode-Valid Parenthese

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 水富县| 闽清县| 眉山市| 特克斯县| 托克逊县| 资阳市| 平顶山市| 绥中县| 泽库县| 清流县| 青河县| 达拉特旗| 民权县| 肇源县| 萍乡市| 江源县| 健康| 马龙县| 托克托县| 静乐县| 青阳县| 金塔县| 樟树市| 金沙县| 九江市| 清镇市| 北辰区| 德兴市| 沭阳县| 崇阳县| 万宁市| 静安区| 长葛市| 登封市| 上虞市| 六枝特区| 土默特右旗| 牡丹江市| 山丹县| 张家口市| 涪陵区|