【笔记 】栈底层 循环队列的处理 链栈 链队列
棧
隊列
解決“假溢出”問題的方法:
采用循環隊列方式:將數組的頭尾看作是相鄰的元素,
即將元素data[0]看作是data[maxlen-1]的下一個元素。如圖所示。
因此,插入和刪除以及狀態檢測需要作相應的調整:
插入操作中移動指示位置的計算:
if ( rear+1 == maxlen ) rear = 0;
else rear++;
或者:rear = ( rear + 1 ) % maxlen ;
或者:rear = ( rear + 1 == maxlen ) ? 0 : rear ++ ;
刪除操作:front = ( front + 1 ) % maxlen ;
隊列空條件: front == rear
入隊與出隊:
error_code queue::append(const elementtype x)
{
if ( full() ) return overflow;
rear = ( rear + 1 ) % maxlen ;
data[rear] = x;
count ++;
return success;
}
error_code queue::serve()
{
if ( empty() ) return underflow;
front = ( front + 1 ) % maxlen;
count --;
return success;
}
分析:
算法的時間復雜度均為O(1).
鏈棧
class stack{
public: // 函數成員
stack();
~stack();
bool empty()const;
bool full()const;
error_code get_top(elementtype &x) const;
error_code push(const elementtyoe x);
error_code pop();
private: // 數據成員
int count;
node * top; //棧頂指針
};
入棧運算的實現 入棧就是將待插入元素裝入一個結點后,連接到鏈表的表頭上。
因此,操作包括:產生結點;裝入元素的值到結點中;
連接結點到表頭–
鏈隊列
class queue{public: // 函數成員queue();~queue();bool empty()const;bool full()const;error_code get_front(elmenttype &x)const;error_code append(const elementtype x);error_code serve();private: // 數據成員int count;node * front, * rear;};
算法如下:
error_code queue::append(const elementtype x ){
node *s = new node;
s -> next = NULL;
s -> data = x; // 封裝
rear -> next = s;
rear = s; //插入
count ++;
return success;
}
總結
以上是生活随笔為你收集整理的【笔记 】栈底层 循环队列的处理 链栈 链队列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【项目实战】vue-springboot
- 下一篇: 【问题记录】解决npm 报错This d