225. Implement Stack using Queues
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<RootNamespace>_225._Implement_Stack_using_Queues</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
50
225. Implement Stack using Queues/MyStack.cs
Normal file
50
225. Implement Stack using Queues/MyStack.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
namespace _225._Implement_Stack_using_Queues;
|
||||
|
||||
public class MyStack
|
||||
{
|
||||
private Queue<int> _queue = new Queue<int>(256);
|
||||
private int? _lastNum = null;
|
||||
|
||||
public MyStack()
|
||||
{
|
||||
}
|
||||
|
||||
public void Push(int x)
|
||||
{
|
||||
if (_lastNum == null)
|
||||
{
|
||||
_lastNum = x;
|
||||
return;
|
||||
}
|
||||
|
||||
int count = _queue.Count;
|
||||
_queue.Enqueue(_lastNum.Value);
|
||||
_lastNum = x;
|
||||
while (count-- > 0)
|
||||
_queue.Enqueue(_queue.Dequeue());
|
||||
}
|
||||
|
||||
public int Pop()
|
||||
{
|
||||
if (_lastNum != null)
|
||||
{
|
||||
int res = _lastNum.Value;
|
||||
_lastNum = null;
|
||||
return res;
|
||||
}
|
||||
|
||||
return _queue.Dequeue();
|
||||
}
|
||||
|
||||
public int Top()
|
||||
{
|
||||
if (_lastNum != null)
|
||||
return _lastNum.Value;
|
||||
return _queue.Peek();
|
||||
}
|
||||
|
||||
public bool Empty()
|
||||
{
|
||||
return _lastNum == null && _queue.Count == 0;
|
||||
}
|
||||
}
|
||||
3
225. Implement Stack using Queues/Program.cs
Normal file
3
225. Implement Stack using Queues/Program.cs
Normal file
@@ -0,0 +1,3 @@
|
||||
// See https://aka.ms/new-console-template for more information
|
||||
|
||||
Console.WriteLine("Hello, World!");
|
||||
Reference in New Issue
Block a user