C++用數(shù)組與鏈表實現(xiàn)棧與雙向隊列

前言

棧是以先進后出,后進先出,隊列是先進先出的原則,一端隊尾插入另一端隊頭取出,雙向隊列相當兩頭都可以插入數(shù)據(jù),兩頭都可以取出數(shù)據(jù)蛙讥。前文了解了ArrayList與LinkedList的實現(xiàn)后,棧與堆的實現(xiàn)就比較簡單了

一:棧的實現(xiàn)

1:Stack基類

template <class E>
class Stack {
protected:
    int len = 0;
public:
    virtual ~Stack();
    virtual int size();
    virtual bool isEmpty();
    //彈出
    virtual E pop() = 0;
    //獲取棧頂不彈出
    virtual E peek() = 0;
    //棧中添加元素
    virtual bool push(const E &e) = 0;
};
template <class E>
Stack<E>::~Stack() {
}
template <class E>
int Stack<E>::size() {
    return len;
}
template <class E>
bool Stack<E>::isEmpty() {
    return len <= 0;
}

2: ArrayStack類

template <class E>
class ArrayStack : public Stack<E> {
private:
    int capacity = 10;
    E *datas = NULL;
public:
    ArrayStack();
    ~ArrayStack();
    E pop();
    E peek();
    bool push(const E &e);
};

template <class E>
ArrayStack<E>::ArrayStack() {
    this->datas = (E*) malloc(sizeof(E) * capacity);
}

template <class E>
ArrayStack<E>::~ArrayStack() {
    if (this->datas) {
        free(this->datas);
        this->datas = NULL;
    }
}

template <class E>
E ArrayStack<E>::pop() {
    assert(Stack<E>::len > 0);
    int index = Stack<E>::len - 1;
    E data = datas[index];
    Stack<E>::len--;
    return data;
}

template <class E>
E ArrayStack<E>::peek() {
    assert(Stack<E>::len > 0);
    return datas[Stack<E>::len - 1];
}

/**
 * 這里忽略擴充數(shù)組后大小超過int最大值
 * @tparam E
 * @param e
 * @return
 */
template <class E>
bool ArrayStack<E>::push(const E &e) {
    if (Stack<E>::len == capacity) //需要擴充
    {
        capacity += capacity >> 1;//擴充成原先的1.5倍
        this->datas = (E*) realloc(this->datas, sizeof(E) * capacity);
    }
    datas[Stack<E>::len] = e;
    Stack<E>::len++;
    return true;
}

3:LinkedStack類

template <class E>
class LinkedStack : public Stack<E> {
private:
    struct Node {
        E data;
        Node *next = NULL;
        Node(const E &data, Node *next) : data(data) {
            this->next = next;
        }
    };
    Node *popNode = NULL;
public:
    ~LinkedStack();
    E pop();
    E peek();
    bool push(const E& e);
};

template <class E>
LinkedStack<E>::~LinkedStack() {
    if (this->popNode) {
        Node *curr = this->popNode;
        while (curr)
        {
            Node *next = curr->next;
            delete curr;
            curr = next;
        }
        this->popNode = NULL;
    }
}

template <class E>
E LinkedStack<E>::pop() {
    assert(Stack<E>::len > 0 && this->popNode);
    Node *next = this->popNode->next;
    E data = this->popNode->data;
    delete this->popNode;
    this->popNode = next;
    Stack<E>::len--;
    return data;
}

template <class E>
E LinkedStack<E>::peek() {
    assert(Stack<E>::len > 0 && this->popNode);
    return this->popNode->data;
}

template <class E>
bool LinkedStack<E>::push(const E &e) {
    Node *newNode = new Node(e, this->popNode);
    this->popNode = newNode;
    Stack<E>::len++;
    return true;
}

二:這里介紹雙向隊列ArrayDeuqe的實現(xiàn)

前文中LinkedList已經(jīng)實現(xiàn)了鏈表式的Deque

1:單向數(shù)組隊列原理

隊列不會像ArrayList那樣會有操作中間某個index的數(shù)據(jù),如果按照ArrayList那種原理的話,每次彈出第一個元素的時候,數(shù)組都要整體移動,這樣大大降低了效率,所以要用到循環(huán)雙向的數(shù)組原理


循環(huán)數(shù)組
單向隊列的添加與刪除

在隊列中數(shù)組的大小必須為2的冥次, 在擴充的時候數(shù)組大小 <<1 原因可以參考前文位運算技巧

單向的添加與刪除
單向隊列擴充
單向隊列擴充
雙向隊列的添加與刪除
雙向隊列

2:ArrayDeque代碼實現(xiàn)

template <class E>
class ArrayDeque {
private:
    static const int DEF_CAPACITY = 16;
    /**
     * 閥值
     */
    int initialCapacity;
    int len = 0;
    /**
     * 隊列頭位置與尾位置
     */
    int headIndex = 0;
    int backIndex = 0;
    E *datas;
    /**
     * 擴充數(shù)組
     */
    void grow();
public:
    ArrayDeque();
    ArrayDeque(int numElements);
    ~ArrayDeque();
    bool isEmpty();
    int size();
    /**
     * 從隊列尾部添加
     */
    bool push(const E &e);
    /**
     * 彈出隊首
     */
    E pop();
    /**
     * 取隊首不彈出
     */
    E peek();
    /**
     * 從隊列首部添加
     */
    bool pushFront(const E &e);
    /**
     * 彈出隊尾數(shù)據(jù)
     */
    E popBack();
    E peekBack();
};

/**
 * 這里忽略擴充數(shù)組后大小超過int最大值
 * @tparam E
 */
template <class E>
void ArrayDeque<E>::grow() {
    int new_size = initialCapacity << 1;
    E *newDatas = (E*) malloc(sizeof(E) * new_size);
    int copyIndex = initialCapacity - backIndex;
    for (int i = 0; i < backIndex; i++) {
        newDatas[copyIndex + i] = datas[i];
    }
    for (int i = 0; i < copyIndex; i++) {
        newDatas[i] = datas[i + backIndex];
    }
    headIndex = 0;
    backIndex = initialCapacity;
    initialCapacity = new_size;
    free(this->datas);
    datas = newDatas;
}

template <class E>
ArrayDeque<E>::ArrayDeque() {
    initialCapacity = DEF_CAPACITY;
    this->datas = (E*) malloc(sizeof(E) * initialCapacity);
}

template <class E>
ArrayDeque<E>::ArrayDeque(int numElements) {
    if (numElements > DEF_CAPACITY) {
        initialCapacity = numElements;
        initialCapacity |= (initialCapacity >> 1);
        initialCapacity |= (initialCapacity >> 2);
        initialCapacity |= (initialCapacity >> 4);
        initialCapacity |= (initialCapacity >> 8);
        initialCapacity |= (initialCapacity >> 16);
        initialCapacity++;
    }
    this->datas = (E*) malloc(sizeof(E) * initialCapacity);
}

template <class E>
ArrayDeque<E>::~ArrayDeque() {
    if (this->datas) {
        free(this->datas);
        this->datas = NULL;
    }
}

template <class E>
bool ArrayDeque<E>::isEmpty() {
    return headIndex == backIndex;
}

template <class E>
int ArrayDeque<E>::size() {
    return this->len;
}

template <class E>
bool ArrayDeque<E>::push(const E &e) {
    headIndex = (headIndex - 1) & (initialCapacity - 1);
    datas[headIndex] = e;
    if (headIndex == backIndex) {//需要擴充
        grow();
    }
    this->len++;
    return true;
}

template <class E>
E ArrayDeque<E>::pop() {
    assert(this->len > 0);
    backIndex = (backIndex - 1) & (initialCapacity - 1);
    E data = datas[backIndex];
    this->len--;
    return data;
}

template <class E>
E ArrayDeque<E>::peek() {
    assert(this->len > 0);
    int popIndex = (backIndex - 1) & (initialCapacity - 1);
    return datas[popIndex];
}

template <class E>
bool ArrayDeque<E>::pushFront(const E &e) {
    datas[backIndex] = e;
    backIndex = (backIndex + 1) & (initialCapacity - 1);
    if (headIndex == backIndex) {//需要擴充
        grow();
    }
    this->len++;
    return true;
}

template <class E>
E ArrayDeque<E>::popBack() {
    assert(this->len > 0);
    E data = datas[headIndex];
    headIndex = (headIndex + 1) & (initialCapacity - 1);
    this->len--;
    return data;
}

template <class E>
E ArrayDeque<E>::peekBack() {
    assert(this->len > 0);
    return datas[headIndex];
}
最后附上源碼https://github.com/youxiaochen/DataStructArrayLink
數(shù)據(jù)結(jié)構(gòu)看10次都不如自己動手敲一次印象深,代碼中如有錯誤歡迎指教

更多文章請關(guān)注:http://www.reibang.com/u/b1cff340957c

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末冤灾,一起剝皮案震驚了整個濱河市塔次,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌阳惹,老刑警劉巖蔬蕊,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件拌滋,死亡現(xiàn)場離奇詭異,居然都是意外死亡雌芽,警方通過查閱死者的電腦和手機授艰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來世落,“玉大人淮腾,你說我怎么就攤上這事√爰眩” “怎么了谷朝?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長武花。 經(jīng)常有香客問我圆凰,道長,這世上最難降的妖魔是什么体箕? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任专钉,我火速辦了婚禮,結(jié)果婚禮上累铅,老公的妹妹穿的比我還像新娘跃须。我一直安慰自己,他們只是感情好娃兽,可當我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布菇民。 她就那樣靜靜地躺著,像睡著了一般换薄。 火紅的嫁衣襯著肌膚如雪玉雾。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天轻要,我揣著相機與錄音复旬,去河邊找鬼。 笑死冲泥,一個胖子當著我的面吹牛驹碍,可吹牛的內(nèi)容都是我干的壁涎。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼志秃,長吁一口氣:“原來是場噩夢啊……” “哼怔球!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起浮还,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤竟坛,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后钧舌,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體担汤,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年洼冻,在試婚紗的時候發(fā)現(xiàn)自己被綠了崭歧。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡撞牢,死狀恐怖率碾,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情屋彪,我是刑警寧澤所宰,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站撼班,受9級特大地震影響歧匈,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜砰嘁,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一件炉、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧矮湘,春花似錦斟冕、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至十办,卻和暖如春秀撇,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背向族。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工呵燕, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人件相。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓再扭,卻偏偏與公主長得像氧苍,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子泛范,可洞房花燭夜當晚...
    茶點故事閱讀 44,713評論 2 354