使用两个栈实现一个队列+使用两个队列实现一个栈

来源:互联网 发布:简述单片机的引脚功能 编辑:程序博客网 时间:2024/06/06 01:09

1. 使用两个栈实现一个队列+使用两个队列实现一个栈

  1. 两个栈实现一个队列

    #include<iostream>#include<stack>using namespace std;template<class T>class StackQueue{public:    void Push(T data)    {        Spush.push(data);    }    void Pop()    {        if (Spop.empty())        {            while (!Spush.empty())            {                Spop.push(Spush.top());                Spush.pop();            }        }        Spop.pop();    }    T Front()    {        if (Spop.empty())        {            while (!Spush.empty())            {                Spop.push(Spush.top());                Spush.pop();            }        }        return Spop.top();    }    bool empty()    {        return Spop.empty() && Spush.empty();    }private:    stack<T> Spop;    stack<T> Spush;};int main(){    StackQueue<int> q;    q.Push(3);    q.Push(4);    q.Push(5);    q.Push(6);    q.Push(7);    q.Push(8);    q.Push(9);    q.Push(10);    while (!q.empty())    {        cout << q.Front() << " ";        q.Pop();    }    system("pause");}
  2. 两个队列实现一个栈

    #include<iostream>#include<queue>using namespace std;template<class T>class QueueStack{public:    void Pop()    {        while (PushQ.size() > 1)        {            PopQ.push(PushQ.front());            PushQ.pop();        }        PushQ.pop();        while (!PopQ.empty())        {            PushQ.push(PopQ.front());            PopQ.pop();        }    }    void Push(T data)    {        PushQ.push(data);    }    T Top()    {        while (PushQ.size() > 1)        {            PopQ.push(PushQ.front());            PushQ.pop();        }        T top=PushQ.front();        PopQ.push(PushQ.front());        PushQ.pop();        while (!PopQ.empty())        {            PushQ.push(PopQ.front());            PopQ.pop();        }        return top;    }    bool Empty()    {        return  PushQ.empty()&& PopQ.empty();    }private:    queue<T> PopQ;    queue<T> PushQ;};int main(){    QueueStack<int> s;    s.Push(5);    s.Push(6);    s.Push(7);    while (!s.Empty())    {        cout << s.Top() << " ";        s.Pop();    }    system("pause");};

2. 将字符串的空格替换成%20

```#include<iostream>using namespace std;int getBlankCount(const char *arr, int len){    int count = 0;    for (int i = 0; i < len; i++)    {        if (arr[i] == ' ')            ++count;    }    return count;}void addTo20(char *arr, int len){    if (arr == nullptr || len <= 0)        return;    int tail = len;    int count = getBlankCount(arr,len);    int end = 2 * count + tail;    while (tail < end)    {        if (arr[tail] == ' ')        {            arr[end--] = '%';            arr[end--] = '0';            arr[end--] = '2';        }        else            arr[end--] = arr[tail];        --tail;    }}int main(){    char arr[100] = " are you ok ";    int len = strlen(arr);    addTo20(arr, len);    cout << arr << endl;    system("pause");}```
原创粉丝点击