首先说一下队列和栈的相同点和不同点:
相同点:
1、都是线性结构。
2、插入操作都是限定在表尾进行
3、都可以通过顺序结构和链式结构实现
4、插入与删除的时间复杂度都是O(1),在空间复杂度上两者也一样
5、多链栈和多队列的管理模式也可以相同
不同点:
1、删除数据元素的位置不同,栈的删除操作在表尾进行,队列的删除操作在表头进行。
2、栈是先进后出,队列是先进先出
3、应用场景不同:常见栈的应用场景包括括号问题的求解,表达式的转换和求值,函数调用和递归实现,深度优先遍历等;
常见的队列的应用场景包括计算机系统中各种资源的管理,消息缓冲区的管理和广度优先搜索遍历等。
两个栈实现队列
思路 : 所有元素压入stack1,然后全部弹出stack并压入stack,实现队列的先进先出。若stack2非空,我们需要的恰好再栈顶,出栈。若要给队列添加元素,即先进入stack;若要出队时,若stack2不为空就出栈,为空就把stack1全部进栈到stack2.
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test1
{
/// <summary>
/// 用两个栈实现队列
/// pushStack实现入队,借助popStack过渡实现出队,当popStack不为空时,直接弹出
/// 为空时,先将pushStack压入popStack并弹出
/// </summary>
class StackToQueue
{
static Stack<int> pushStack = new Stack<int>(); //进的栈
static Stack<int> popStack = new Stack<int>(); //出的栈
//进栈
public static void push(int node)
{
while (popStack.Count > 0)
{
pushStack.Push(popStack.Pop());
}
pushStack.Push(node);
}
//出栈
public static int pop()
{
while (pushStack.Count > 0)
{
popStack.Push(pushStack.Pop());
}
return popStack.Pop();
}
}
}
两个队列实现栈:
思路 : 将queue1实现进栈,queue2过渡实现出栈,如果queue1为空queue2等于1时,直接弹出。如果queue1为空queue2大于1时,将queue2中数据弹出压入queue1中,如果queue1大于1时,将queue1中数据弹出压入queue2中。
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test1
{
/// <summary>
/// 用两个队列实现栈
/// enQueue实现入栈,借助deQueue过渡实现出栈,如果enQueue为空deQueue等于1时,直接弹出、
/// 如果enQueue为空deQueue大于1时,将deQueue中数据弹出压入enQueue中。
/// 如果enQueue大于1时,将enQueue中数据弹出压入deQueue中
/// </summary>
class QueueToStack
{
static Queue<int> enQueue = new Queue<int>();
static Queue<int> deQueue = new Queue<int>();
//进队列
public static void EnQueue(int node)
{
enQueue.Enqueue(node);
}
//出队列
public static int DeQueue()
{
if (enQueue.Count == 0)
{
if (deQueue.Count == 0)
{
Console.WriteLine("队列为空");
}
else
{
while (deQueue.Count > 1)
{
enQueue.Enqueue(deQueue.Dequeue());
}
return deQueue.Dequeue();
}
while (enQueue.Count > 1)
{
deQueue.Enqueue(enQueue.Dequeue());
}
}
return enQueue.Dequeue();
}
}
}