如何使用兩個堆棧實現隊列_使用兩個隊列實現堆棧

如何使用兩個堆棧實現隊列

Stack and Queue at a glance...

堆疊和排隊一目了然...

Stack:

堆棧:

The stack is an ordered list where insertion and deletion are done from the same end, top. The last element that entered first is the first one to be deleted (the basic principle behind the LIFO). That means it is a data structure which is implemented as LIFO.

堆棧是一個有序列表,其中插入和刪除從同一末端開始。 首先輸入的最后一個元素是要刪除的第一個元素(LIFO的基本原理)。 這意味著它是一個實現為LIFO的數據結構。

The main stack operations are (basic ADT operations)...

主堆棧操作為(基本ADT操作)...

  1. push (int data): Insertion at top

    push(int數據):在頂部插入

  2. int pop(): Deletion from top

    int pop():從頂部刪除

Queue:

隊列:

The queue is an ordered list in which insertions are done at one end (rear) and deletions are done from another end (front). The first element that got inserted is the first one to be deleted (basic principle of FIFO). That means it is a data structure which is implemented as FIFO.

隊列是一個有序列表,其中插入是在一端(后部)完成,而刪除是從另一端(前部)完成。 插入的第一個元素是要刪除的第一個元素(FIFO的基本原理)。 這意味著它是一個實現為FIFO的數據結構。

The main Queue operations are (basic ADT operations)...

主要的Queue操作是(基本ADT操作)...

  1. EnQueue (int data): Insertion at rear end

    EnQueue(int數據):在后端插入

  2. int DeQueue(): Deletion from front end

    int DeQueue():從前端刪除

使用兩個隊列實現堆棧 (Implementation of a stack using two queues)

Likewise, a queue can be implemented with two stacks, a stack can also be implemented using two queues. The basic idea is to perform stack ADT operations using the two queues.

同樣,一個隊列可以用兩個堆棧實現,一個堆棧也可以用兩個隊列實現。 基本思想是使用兩個隊列執行堆棧ADT操作。

So, we need to implement push(),pop() using DeQueue(), EnQueue() operations available for the queues.

因此,我們需要使用隊列可用的DeQueue()和EnQueue()操作來實現push(),pop()。

Implementation:

實現方式:

Let q1 and q2 be the two queues...

設q1和q2為兩個隊列...

struct stack{
struct queue *q1;
struct queue *q2;
}

Algorithm to implement push and pop:

實現推送和彈出的算法:

Push operation algorithm:

推送操作算法:

  1. Check whether q1 is empty or not. If q1 is empty then EnQueue the element to q2.

    檢查q1是否為空。 如果q1為空,則將元素排隊到q2。

  2. Otherwise EnQueue to q1.

    否則,排隊到q1。

push(struct stack *s,int data){
if(isempty(s->q1))
EnQueue(s->q2,data);
else
EnQueue(s->q1,data);
}

Pop operation algorithm

彈出操作算法

The basic idea is to transfer n-1 elements (let n be the total no of elements) to other queue and delete the last one from a queue to perform the pop operation.

基本思想是將n-1個元素(使n為元素總數)轉移到其他隊列,并從隊列中刪除最后一個元素以執行彈出操作。

  1. If q1 is not empty then transfer n-1 elements from q1 to q2 and DeQueue the last element and return it.

    如果q1不為空,則將n-1個元素從q1傳輸到q2,并對最后一個元素進行DeQueue并返回。

  2. If q2 is not empty then transfer n-1 elements from q2 to q1 and DeQueue the last element and return it.

    如果q2不為空,則將n-1個元素從q2傳輸到q1,并對最后一個元素進行DeQueue并返回。

int pop(struct stack *s){
int count,size;
if(isempty(s->q2)){
size=Size(s->q1);
count=0;
while(count<size-1){
//transferring n-1 elements
EnQueue(s->q2,DeQueue(s->q1));
count++;
}
//last element to be popped
return DeQueue(s->q1);
}
else{
size=Size(s->q2);
count=0;
while(count<size-1){
EnQueue(s->q1,DeQueue(s->q2));
count++;
}
return DeQueue(s->q1);
}
}

Time complexity analysis:

時間復雜度分析:

  1. Push: O(1)

    推:O(1)

  2. Pop: O(n) , since transferring n-1 elements

    彈出:O(n),因為傳輸了n-1個元素

使用C ++的實現代碼(使用STL) (Implementation code using C++ (using STL))

#include <bits/stdc++.h>
using namespace std;
struct Stack{
queue<int> q1,q2;
void push(int x){
if(q1.empty()){
q2.push(x);    //EnQueue operation using STL
}
else{
q1.push(x);    //EnQueue operation using STL
}
}
int pop(){
int count,size,item;
if(q2.empty()){
size=q1.size();            //size=no of elements;
count=0;
while(count<size-1){         //transfering n-1 elements
q2.push(q1.front());     // DeQueue operation using STL
q1.pop();
count++;
}
item=q1.front();
q1.pop();
return item;                 //popping out the element
}
else{
size=q2.size();
count=0;
while(count<size-1){
q1.push(q2.front());
q2.pop();
count++;
}
item=q2.front();
q2.pop();
return item;
}
}
};
int main()
{
cout<<"implementing stack with two queues"<<endl;
cout<<"enter any integer to push and 0 to stop pushing"<<endl;
Stack s;
int x,count=0;
cin>>x;
while(x){
s.push(x);
cin>>x;
count++;
}
cout<<"now popping......."<<endl;
while(count){
cout<<s.pop()<<endl;
count--;
}
cout<<"executed successfully!!!"<<endl;
return 0;
}

Output

輸出量

implementing stack with two queues
enter any integer to push and 0 to stop pushing
1
2
3
0
now popping.......
3
2
1
executed successfully!!!

翻譯自: https://www.includehelp.com/data-structure-tutorial/implementation-of-stack-using-two-queues.aspx

如何使用兩個堆棧實現隊列

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/379977.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/379977.shtml
英文地址,請注明出處:http://en.pswp.cn/news/379977.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

接口pk抽象類

作為開發者&#xff0c;誰從來沒有陷入過周而復始地爭論應該是使用接口還是抽象類&#xff1f;這是一場永無休止的爭論&#xff0c;不同陣營的人總是堅定地堅持自己的立場。應當使用接口還是抽象類&#xff1f;對于初學者來說那更是滿頭霧水。這個問題應該考慮一下幾個因素&…

匯編shr命令

右移命令 比如&#xff1a; mov eax,10 shr eax,0x2上面的命令是將eax的值右移兩位&#xff0c;怎么左移呢&#xff1f;首先將eax的值轉為二進制10------》1010&#xff0c;然后右移兩位變成10&#xff0c;所以執行為shr命令&#xff0c;eax的值為十進制的2

iBatis入門和開發環境搭建

iBatis 的優缺點&#xff1a; 優點&#xff1a; 1、 減少代碼量&#xff0c;簡單&#xff1b; 2、 性能增強&#xff1b; 3、 Sql 語句與程序代碼分離&#xff1b; 4、 增強了移植性&#xff1b; 缺點&#xff1a; 1、 和Hibernate 相比&#xff0c;sql 需要自己寫&#x…

Python | 程序以字符串長度打印單詞

Given a string and we have to split the string into words and also print the length of the each word in Python. 給定一個字符串&#xff0c;我們必須將字符串拆分為單詞&#xff0c;并在Python中打印每個單詞的長度。 Example: 例&#xff1a; Input:str "Hell…

Java——遞歸練習

#練習一&#xff1a;從鍵盤接收一個文件夾路徑&#xff0c;統計該文件夾大小 ###分析&#xff1a; ####每句話相當與每一個要求&#xff0c;每一個要求用一個方法去實現 第一個方法 * getDir()* 第一個要求&#xff1a;從鍵盤接收一個文件夾路徑* 1&#xff0c;創建鍵盤錄入對…

C# 里怎樣得到當前執行的函數名,當前代碼行,源代碼文件名。

得到函數名&#xff1a; System.Diagnostics.StackTrace st new System.Diagnostics.StackTrace(); this.Text st.GetFrame(0).ToString(); 得到代碼行&#xff0c;源代碼文件名&#xff1a; StackTrace st new StackTrace(new StackFrame(true)); Console…

PHP中單引號和雙引號的區別

0x01 單引號 單引號里面的內容不會被解釋&#xff0c;不管什么內容&#xff0c;都當做字符串處理 <?php$abc1234; $stradc$abc; echo $str;輸出 0x02 雙引號 雙引號里面的內容會被解釋&#xff0c;像一些換行&#xff08;\n)、數據元素等都會被解釋 <?php$abc1234;…

Eclipse 代碼提示無效的解決方法

代碼提示一般有兩種形勢1、點提示無效經常打一個點就能調出該對象可選的方法列表。哪天不靈了&#xff0c;可以這樣解決&#xff1a;window->Preferences->Java->Editor->Content Assist->Advanced 上面的選項卡Select the proposal kinds contained in the de…

getdate 日期間隔_日期getDate()方法以及JavaScript中的示例

getdate 日期間隔JavaScript Date getDate()方法 (JavaScript Date getDate() method) getDate() method is a Dates class method and it is used to get the current day of the month. getDate()方法是Date的類方法&#xff0c;用于獲取當月的當前日期。 It accepts nothin…

關閉頁面時執行“退出”的解決方案

在有些應用中我們需要實時的更新站點用戶是否在線的狀態。比如一些論壇里的在線成員實時顯示&#xff0c;或基于網頁的聊天、會議系統等。這種情況下&#xff0c;如果用戶點擊“退出”按鈕或鏈接&#xff0c;我們將之行一系列后臺操作&#xff0c;將該用戶標識成off line狀態&a…

Java——多線程實現的三種方式

創建新執行線程有三種方法。 第一種方法是將類聲明為 Thread 的子類。該子類應重寫 Thread 類的 run 方法。接下來可以分配并啟動該子類的實例。 例如&#xff0c;計算大于某一規定值的質數的線程可以寫成&#xff1a; class PrimeThread extends Thread {long minPrime;Pri…

python網絡編程---TCP客戶端

0x01 環境 python2、 pycharm 0x02 程序 # -*- coding:UTF-8 -*- import sockettarget_hostwww.baidu.com tarfet_port80target_hostlocalhost target_port3345 dataABCDEF# 創建一個socket對象 client socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 連接客戶端 clien…

c#枚舉數字轉枚舉_C#枚舉能力問題和解答 套裝4

c#枚舉數字轉枚舉1) What is the correct output of given code snippets in C#.NET? using System;class program{enum emp_salary : int{emp1 10000,emp2 15000,emp4 20000}static void Main(string[] args){int sal (int)emp_salary.emp2;Console.WriteLine(sal);}}100…

Java——匿名內部類實現線程的兩種方式

package com.yy.thread;public class Demo4_Thread {public static void main(String[] args) {demo1(); //匿名內部類&#xff0c;第一種&#xff0c;繼承Threaddemo2(); //匿名內部類&#xff0c;第二種&#xff0c;實現Runnable接口 }private static void…

zlib1.2.5的編譯

zlib1.2.5沒有了1.2.4的vc6工程&#xff0c;只好使用命令行編譯。通過win32/Makefile.msc發現有4種編譯方式&#xff0c;如下&#xff1a;# Usage:# nmake -f win32/Makefile.msc (standard build)# nmake -f win32/Makefile.msc LOC-DFOO …

python網絡編程--UDP客戶端

0x01 環境 python、pycharm 0x02 程序 # -*- coding:utf-8 -*-import sockettarget_host127.0.0.1 target_part80#創建一個socket對象 client socket.socket(socket.AF_INET,socket.SOCK_DGRAM)#發送一些數據 client.sendto(AAAAAA,(target_host,target_part))#接收到的消息 …

window.open參數和技巧

【1、最基本的彈出窗口代碼】 <SCRIPT LANGUAGE"javascript"> <!-- window.open (page.html) --> </SCRIPT> 因為著是一段javascripts代碼&#xff0c;所以它們應該放在<SCRIPT LANGUAGE"javascript">標簽和</script>之間。…

java jar包示例_Java包getImplementationTitle()方法和示例

java jar包示例包類的getImplementationTitle()方法 (Package Class getImplementationTitle() method) getImplementationTitle() method is available in java.lang package. getImplementationTitle()方法在java.lang包中可用。 getImplementationTitle() method is used to…

Java——獲取和設置多線程的名稱

給名字進行賦值有兩種方式&#xff1a; 1&#xff0c;通過構造去賦值 Thread(String name) 直接在構造方法里面傳一個名字就行了2&#xff0c;通過set設置的方法進行賦值 package com.yy.threadmethod;public class Demo1_Name {public static void main(String[] args) {dem…

十三、oracle 數據字典和動態性能視圖

一、概念數據字典是oracle數據庫中最重要的組成部分&#xff0c;它提供了數據庫的一些系統信息。動態性能視圖記載了例程啟動后的相關信息。 二、數據字典1)、數據字典記錄了數據庫的系統信息&#xff0c;它是只讀表和視圖的集合&#xff0c;數據字典的所有者為sys用戶。2)、用…