📌  相关文章
📜  查找 Stack 和 Queue 的共同元素

📅  最后修改于: 2022-05-13 01:56:07.451000             🧑  作者: Mango

查找 Stack 和 Queue 的共同元素

给定一堆M元素和一个按排序顺序排列的N个元素的队列。任务是找出栈和队列的共同元素。

例子:

方法:给定的问题可以借助以下思想来解决:

请按照下图更好地理解。

插图:

请按照以下步骤解决问题:

  • 反转队列。
  • 遍历栈和队列,同时栈和队列不为空。
    • 如果栈顶=队列的前面,那是一个公共元素。
    • 否则,如果栈顶 > 队列前面,则弹出栈顶元素。
    • 否则,栈顶<队列前端,弹出栈顶元素。
  • 打印公共元素。

下面是上述方法的实现:

C++
// C++ code to implement the above approach
  
#include 
using namespace std;
  
// Function to find common element
// of stack and queue
vector findCommonElement(stack& St,
                              queue& Q)
{
    // Initialize size of queue Q to 0
    int Size = 0;
    vector v;
  
    // Put every element of queue into stack
    // and calculate size of queue
    while (!Q.empty()) {
        St.push(Q.front());
        Q.pop();
        Size++;
    }
  
    // Put extra element of stack into queue
    // again extra element of stack is the
    // element coming from queue. Now, the
    // queue is reverse
    while (Size != 0) {
        Q.push(St.top());
        St.pop();
        Size--;
    }
  
    // Traverse while stack and queue is not
    // empty
    while (!St.empty() && !Q.empty()) {
        // Top element of stack
        int a = St.top();
  
        // Front element of queue
        int b = Q.front();
  
        // Push the common element
        // in vector if a = b
        if (a == b)
            v.push_back(a);
  
        // Else pop the larger value
        // from its container
        (a > b) ? St.pop() : Q.pop();
    }
    return v;
}
  
// Driver Code
int main()
{
    stack St;
    queue Q;
  
    // Fill element into stack
    St.push(1);
    St.push(3);
    St.push(5);
    St.push(7);
  
    // Fill element into queue
    Q.push(1);
    Q.push(2);
    Q.push(5);
    Q.push(9);
  
    // Find common element if exists
    vector v = findCommonElement(St, Q);
  
    if (v.size() == 0)
        cout << "Not Found" << endl;
    for (auto i : v)
        cout << i << " ";
    return 0;
}


输出
5 1 

时间复杂度: O(M+N)
辅助空间: O(1)