📜  检查是否可以使用堆栈将一个队列分类到另一个队列中

📅  最后修改于: 2021-05-04 10:38:28             🧑  作者: Mango

给定一个由前n个自然数组成的队列(随机顺序)。任务是检查是否可以使用堆栈将给定的Queue元素按升序排列在另一个Queue中。允许的操作是:
1.从堆栈中推入和弹出元素
2.从给定的队列中弹出(或入队)。
3.在另一个队列中推送(或出队)。

例子 :

观察,第二个Queue(将包含已排序的元素)从给定的Queue或Stack中获取输入(或排队元素)。因此,下一个预期的元素(最初将是1)必须作为给定Queue的前元素或Stack的顶层元素出现。因此,只需将期望的元素初始化为1即可模拟第二个Queue的过程,并检查是否可以从给定Queue的顶部或堆栈的顶部获取期望的元素。如果我们不能从其中任何一个中获取它,则弹出给定Queue的最前面的元素,并将其推入堆栈。
另外,请注意,堆栈也必须在每个实例中都进行排序,即,堆栈顶部的元素必须在堆栈中最小。例如。令x> y,则x总是在y之前。因此,不能将x推入堆栈中的y之前。因此,我们不能将具有较高值的元素推到具有较小值的元素的顶部。

算法:
1.初始化Expected_element = 1
2.检查给定Queue的最前面的元素或堆栈的最前面的元素是否具有Expected_element
….a)如果是,则将Expected_element加1,重复步骤2。
….b)否则,弹出Queue的前面,并将其推入堆栈。如果弹出的元素大于堆栈顶部,则返回“否”。

以下是此方法的实现:

C++
// CPP Program to check if a queue of first 
// n natural number can be sorted using a stack
#include 
using namespace std;
  
// Function to check if given queue element 
// can be sorted into another queue using a
// stack.
bool checkSorted(int n, queue& q)
{
    stack st;
    int expected = 1;
    int fnt;
  
    // while given Queue is not empty.
    while (!q.empty()) {
        fnt = q.front();
        q.pop();
  
        // if front element is the expected element
        if (fnt == expected)
            expected++;
  
        else {
            // if stack is empty, push the element
            if (st.empty()) {
                st.push(fnt);
            }
  
            // if top element is less than element which
            // need to be pushed, then return fasle.
            else if (!st.empty() && st.top() < fnt) {
                return false;
            }
  
            // else push into the stack.
            else
                st.push(fnt);
        }
  
        // while expected element are coming from
        // stack, pop them out.
        while (!st.empty() && st.top() == expected) {
            st.pop();
            expected++;
        }
    }
  
    // if the final expected element value is equal
    // to initial Queue size and the stack is empty.
    if (expected - 1 == n && st.empty())
        return true;
  
    return false;
}
  
// Driven Program
int main()
{
    queue q;
    q.push(5);
    q.push(1);
    q.push(2);
    q.push(3);
    q.push(4);
  
    int n = q.size();
  
    (checkSorted(n, q) ? (cout << "Yes") :
                         (cout << "No"));
  
    return 0;
}


Java
// Java Program to check if a queue 
// of first n natural number can
// be sorted using a stack
import java.io.*;
import java.util.*;
  
class GFG
{
    static Queue q = 
                    new LinkedList();
      
    // Function to check if given 
    // queue element can be sorted 
    // into another queue using a stack.
    static boolean checkSorted(int n)
    {
        Stack st = 
                    new Stack();
        int expected = 1;
        int fnt;
      
        // while given Queue
        // is not empty.
        while (q.size() != 0) 
        {
            fnt = q.peek();
            q.poll();
      
            // if front element is 
            // the expected element
            if (fnt == expected)
                expected++;
      
            else
            {
                // if stack is empty, 
                // push the element
                if (st.size() == 0) 
                {
                    st.push(fnt);
                }
      
                // if top element is less than 
                // element which need to be 
                // pushed, then return fasle.
                else if (st.size() != 0 && 
                         st.peek() < fnt) 
                {
                    return false;
                }
      
                // else push into the stack.
                else
                    st.push(fnt);
            }
      
            // while expected element are
            // coming from stack, pop them out.
            while (st.size() != 0 && 
                   st.peek() == expected) 
            {
                st.pop();
                expected++;
            }
        }
          
        // if the final expected element 
        // value is equal to initial Queue
        // size and the stack is empty.
        if (expected - 1 == n && 
                st.size() == 0)
            return true;
      
        return false;
    }
      
    // Driver Code
    public static void main(String args[])
    {
        q.add(5);
        q.add(1);
        q.add(2);
        q.add(3);
        q.add(4);
      
        int n = q.size();
  
        if (checkSorted(n))
            System.out.print("Yes");
        else
            System.out.print("No");
    }
}
  
// This code is contributed by 
// Manish Shaw(manishshaw1)


Python3
# Python Program to check if a queue of first 
# n natural number can be sorted using a stack 
from queue import Queue 
  
# Function to check if given queue element 
# can be sorted into another queue using a 
# stack. 
def checkSorted(n, q):
    st = [] 
    expected = 1
    fnt = None
  
    # while given Queue is not empty. 
    while (not q.empty()): 
        fnt = q.queue[0] 
        q.get() 
  
        # if front element is the 
        # expected element 
        if (fnt == expected): 
            expected += 1
  
        else:
              
            # if stack is empty, put the element 
            if (len(st) == 0):
                st.append(fnt)
  
            # if top element is less than element which 
            # need to be puted, then return fasle. 
            elif (len(st) != 0 and st[-1] < fnt): 
                return False
  
            # else put into the stack. 
            else:
                st.append(fnt)
  
        # while expected element are coming 
        # from stack, pop them out. 
        while (len(st) != 0 and 
                   st[-1] == expected): 
            st.pop() 
            expected += 1
  
    # if the final expected element value is equal 
    # to initial Queue size and the stack is empty. 
    if (expected - 1 == n and len(st) == 0): 
        return True
  
    return False
  
# Driver Code
if __name__ == '__main__':
    q = Queue()
    q.put(5) 
    q.put(1) 
    q.put(2) 
    q.put(3) 
    q.put(4) 
  
    n = q.qsize() 
  
    if checkSorted(n, q):
        print("Yes")
    else:
        print("No")
  
# This code is contributed by PranchalK


C#
// C# Program to check if a queue 
// of first n natural number can
// be sorted using a stack
using System;
using System.Linq;
using System.Collections.Generic;
  
class GFG
{
    // Function to check if given 
    // queue element can be sorted 
    // into another queue using a stack.
    static bool checkSorted(int n, 
                            ref Queue q)
    {
        Stack st = new Stack();
        int expected = 1;
        int fnt;
      
        // while given Queue
        // is not empty.
        while (q.Count != 0) 
        {
            fnt = q.Peek();
            q.Dequeue();
      
            // if front element is 
            // the expected element
            if (fnt == expected)
                expected++;
      
            else 
            {
                // if stack is empty, 
                // push the element
                if (st.Count != 0) 
                {
                    st.Push(fnt);
                }
      
                // if top element is less than 
                // element which need to be 
                // pushed, then return fasle.
                else if (st.Count != 0 && 
                         st.Peek() < fnt) 
                {
                    return false;
                }
      
                // else push into the stack.
                else
                    st.Push(fnt);
            }
      
            // while expected element are
            // coming from stack, pop them out.
            while (st.Count != 0 && 
                   st.Peek() == expected) 
            {
                st.Pop();
                expected++;
            }
        }
        // if the final expected element 
        // value is equal to initial Queue
        // size and the stack is empty.
        if (expected - 1 == n && 
                st.Count == 0)
            return true;
      
        return false;
    }
      
    // Driver Code
    static void Main()
    {
        Queue q = new Queue();
        q.Enqueue(5);
        q.Enqueue(1);
        q.Enqueue(2);
        q.Enqueue(3);
        q.Enqueue(4);
      
        int n = q.Count;
  
        if (checkSorted(n, ref q))
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}
  
// This code is contributed by 
// Manish Shaw(manishshaw1)


输出 :
Yes

视频由Parul Shandilya提供