Implement Stack using Two Queues

后端 未结 23 634
感情败类
感情败类 2020-11-28 17:05

A similar question was asked earlier there, but the question here is the reverse of it, using two queues as a stack. The question...

Given two queues with their sta

相关标签:
23条回答
  • 2020-11-28 17:32
    Q1 = [10, 15, 20, 25, 30]
    Q2 = []
    
    exp:
    {   
        dequeue n-1 element from Q1 and enqueue into Q2: Q2 == [10, 15, 20, 25]
    
        now Q1 dequeue gives "30" that inserted last and working as stack
    }
    
    swap Q1 and Q2 then GOTO exp
    
    0 讨论(0)
  • 2020-11-28 17:33
    import java.util.*;
    
    /**
     *
     * @author Mahmood
     */
    public class StackImplUsingQueues {
    
        Queue<Integer> q1 = new LinkedList<Integer>();
        Queue<Integer> q2 = new LinkedList<Integer>();
    
        public int pop() {
            if (q1.peek() == null) {
                System.out.println("The stack is empty, nothing to return");
                int i = 0;
                return i;
            } else {
                int pop = q1.remove();
                return pop;
            }
        }
    
        public void push(int data) {
    
            if (q1.peek() == null) {
                q1.add(data);
            } else {
                for (int i = q1.size(); i > 0; i--) {
                    q2.add(q1.remove());
                }
                q1.add(data);
                for (int j = q2.size(); j > 0; j--) {
                    q1.add(q2.remove());
                }
    
            }
        }
    
        public static void main(String[] args) {
            StackImplUsingQueues s1 = new StackImplUsingQueues();
            //       Stack s1 = new Stack();
            s1.push(1);
            s1.push(2);
            s1.push(3);
            s1.push(4);
            s1.push(5);
            s1.push(6);
            s1.push(7);
            s1.push(8);
            s1.push(9);
            s1.push(10);
            // s1.push(6);
            System.out.println("1st = " + s1.pop());
            System.out.println("2nd = " + s1.pop());
            System.out.println("3rd = " + s1.pop());
            System.out.println("4th = " + s1.pop());
            System.out.println("5th = " + s1.pop());
            System.out.println("6th = " + s1.pop());
            System.out.println("7th = " + s1.pop());
            System.out.println("8th = " + s1.pop());
            System.out.println("9th = " + s1.pop());
            System.out.println("10th= " + s1.pop());
        }
    }
    
    0 讨论(0)
  • 2020-11-28 17:33
    #include "stdio.h"
    #include "stdlib.h"
    
    typedef struct {
        int *q;
        int size;
        int front;
        int rear;
    } Queue;
    typedef struct {
        Queue *q1;
        Queue *q2;
    } Stack;
    
    int queueIsEmpty(Queue *q) {
        if (q->front == -1 && q->rear == -1) {
            printf("\nQUEUE is EMPTY\n");
            return 1;
        }
        return 0;
    }
    int queueIsFull(Queue *q) {
        if (q->rear == q->size-1) {
            return 1;
        }
        return 0;
    }
    int queueTop(Queue *q) {
        if (queueIsEmpty(q)) {
            return -1;
        }
        return q->q[q->front];
    }
    int queuePop(Queue *q) {
        if (queueIsEmpty(q)) {
            return -1;
        }
        int item = q->q[q->front];
        if (q->front == q->rear) {
            q->front = q->rear = -1;
        }
        else {
            q->front++;
        }
        return item;
    }
    void queuePush(Queue *q, int val) {
        if (queueIsFull(q)) {
            printf("\nQUEUE is FULL\n");
            return;
        }
        if (queueIsEmpty(q)) {
            q->front++;
            q->rear++;
        } else {
            q->rear++;
        }
        q->q[q->rear] = val;
    }
    Queue *queueCreate(int maxSize) {
        Queue *q = (Queue*)malloc(sizeof(Queue));
        q->front = q->rear = -1;
        q->size = maxSize;
        q->q = (int*)malloc(sizeof(int)*maxSize);
        return q;
    }
    /* Create a stack */
    void stackCreate(Stack *stack, int maxSize) {
        Stack **s = (Stack**) stack;
        *s = (Stack*)malloc(sizeof(Stack));
        (*s)->q1 = queueCreate(maxSize);
        (*s)->q2 = queueCreate(maxSize);
    }
    
    /* Push element x onto stack */
    void stackPush(Stack *stack, int element) {
        Stack **s = (Stack**) stack;
        queuePush((*s)->q2, element);
        while (!queueIsEmpty((*s)->q1)) {
            int item = queuePop((*s)->q1);
            queuePush((*s)->q2, item);
        }
        Queue *tmp = (*s)->q1;
        (*s)->q1 = (*s)->q2;
        (*s)->q2 = tmp;
    }
    
    /* Removes the element on top of the stack */
    void stackPop(Stack *stack) {
        Stack **s = (Stack**) stack;
        queuePop((*s)->q1);
    }
    
    /* Get the top element */
    int stackTop(Stack *stack) {
        Stack **s = (Stack**) stack;
        if (!queueIsEmpty((*s)->q1)) {
          return queueTop((*s)->q1);
        }
        return -1;
    }
    
    /* Return whether the stack is empty */
    bool stackEmpty(Stack *stack) {
        Stack **s = (Stack**) stack;
        if (queueIsEmpty((*s)->q1)) {
            return true;
        }
        return false;
    }
    
    /* Destroy the stack */
    void stackDestroy(Stack *stack) {
        Stack **s = (Stack**) stack;
        free((*s)->q1);
        free((*s)->q2);
        free((*s));
    }
    
    int main()
    {
      Stack *s = NULL;
      stackCreate((Stack*)&s, 10);
      stackPush((Stack*)&s, 44);
      //stackPop((Stack*)&s);
      printf("\n%d", stackTop((Stack*)&s));
      stackDestroy((Stack*)&s);
      return 0;
    }
    
    0 讨论(0)
  • 2020-11-28 17:36
    #include <bits/stdc++.h>
    using namespace std;
    queue<int>Q;
    stack<int>Stk;
    void PRINT(stack<int>ss , queue<int>qq) {
        while( ss.size() ) {
            cout << ss.top() << " " ;
            ss.pop();
        }
        puts("");
        while( qq.size() ) {
            cout << qq.front() << " " ;
            qq.pop();
        }
        puts("\n----------------------------------");
    }
    void POP() {
        queue<int>Tmp ;
        while( Q.size() > 1 ) {
            Tmp.push( Q.front()  );
            Q.pop();
        }
        cout << Q.front() << " " << Stk.top() << endl;
        Q.pop() , Stk.pop() ;
        Q = Tmp ;
    }
    void PUSH(int x ) {
        Q.push(x);
        Stk.push(x);
    }
    int main() {
        while( true ) {
            string typ ;
            cin >> typ ;
            if( typ == "push" ) {
                int x ;
                cin >> x;
                PUSH(x);
            } else POP();
            PRINT(Stk,Q);
        }
    }
    
    0 讨论(0)
  • 2020-11-28 17:37

    here is the complete working code in c# :

    It has been implemented with Single Queue,

    push:

    1. add new element.
    2. Remove elements from Queue (totalsize-1) times and add back to the Queue
    

    pop:

    normal remove
    
    
    
    
    
     using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;
    
        namespace StackImplimentationUsingQueue
        {
            class Program
            {
                public class Node
                {
                    public int data;
                    public Node link;
                }
                public class Queue
                {
                    public Node rear;
                    public Node front;
                    public int size = 0;
                    public void EnQueue(int data)
                    {
                        Node n = new Node();
                        n.data = data;
                        n.link = null;
                        if (rear == null)
                            front = rear = n;
                        else
                        {
                            rear.link = n;
                            rear = n;
                        }
                        size++;
                        Display();
                    }
                    public Node DeQueue()
                    {
                        Node temp = new Node();
                        if (front == null)
                            Console.WriteLine("Empty");
                        else
                        {
                            temp = front;
                            front = front.link;
                            size--;
                        }
                        Display();
                        return temp;
                    }
                    public void Display()
                    {
                        if (size == 0)
                            Console.WriteLine("Empty");
                        else
                        {
                            Console.Clear();
                            Node n = front;
                            while (n != null)
                            {
                                Console.WriteLine(n.data);
                                n = n.link;
                            }
                        }
                    }
                }
                public class Stack
                {
                    public Queue q;
                    public int size = 0;
                    public Node top;
                    public Stack()
                    {
                        q = new Queue();
                    }
                    public void Push(int data)
                    {
                        Node n = new Node();
                        n.data = data;
                        q.EnQueue(data);
                        size++;
                        int counter = size;
                        while (counter > 1)
                        {
                            q.EnQueue(q.DeQueue().data);
                            counter--;
                        }
                    }
                    public void Pop()
                    {
                        q.DeQueue();
                        size--;
                    }
                }
                static void Main(string[] args)
                {
                    Stack s= new Stack();
                    for (int i = 1; i <= 3; i++)
                        s.Push(i);
                    for (int i = 1; i < 3; i++)
                        s.Pop();
                    Console.ReadKey();
                }
            }
        }
    
    0 讨论(0)
  • 2020-11-28 17:44

    Can we just use one queue to implement a stack? I can use two queues, but considering single queue would be more efficient. Here is the code:

        public void Push(T val)
        {
            queLower.Enqueue(val);
        }
    
        public  T Pop()
        {
    
            if (queLower.Count == 0 )
            {
                Console.Write("Stack is empty!");
                return default(T);
    
             }
            if (queLower.Count > 0)
            {
                for (int i = 0; i < queLower.Count - 1;i++ )
                {
                    queLower.Enqueue(queLower.Dequeue ());
               }
                        }
    
            return queLower.Dequeue();
    
        }
    
    0 讨论(0)
提交回复
热议问题