Create prgram in C# Read https://msdn.microsoft.com/en-us/library/7977ey2c(v=vs.
ID: 3828897 • Letter: C
Question
Create prgram in C#
Read https://msdn.microsoft.com/en-us/library/7977ey2c(v=vs.110).aspx
to learn Queue class.
Based on "StackTest" Example, convert Stack to Queue.
1. Use Queue method Enqueue() to add items to Queue
2. Dequeue to remove items.
3. Peek to peek itmes.
Explanation / Answer
Here is the C# program to convert stack to queue,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QueueImplementationUsingStack
{
class Program
{
public class Stack<T> //Declare class stack
{
public int size;
public Node<T> head;
public void Push(T data) //Add a new element into stack
{
Node<T> node = new Node<T>();
node.data = data;
if (head == null) //checks if stack is full
head = node;
else
{
node.link = head; //push an element into the stack
head = node;
}
size++;
Display();
}
public Node<T> Pop() //removes an element from the stack
{
if (head == null)
return null;
else
{
Node<T> temp = head;
//temp.link = null;
head = head.link;
size--; // removes the element from the stack
Display();
return temp;
}
}
public Node<T> Peek() //displays the top most element in the stack
{
if (isEmpty())
{
Console.WriteLine("Stack is empty!");
return "No elements";
}
else
{
Node<T> temp = head;
Display();
}
}
public void Display()
{
if (size == 0)
Console.WriteLine("Empty");
else
{
Console.Clear();
Node<T> temp = head;
while (temp!= null)
{
Console.WriteLine(temp.data);
temp = temp.link;
}
}
}
}
public class Queue<T> //create a class Queue
{
public int size;
public Stack<T> inbox;
public Stack<T> outbox;
public Stack<T> peek;
public Queue()
{
inbox = new Stack<T>();
outbox = new Stack<T>();
peek= new Stack<T>();
}
public void EnQueue(T data) //Add an element in the queue
{
inbox.Push(data);
size++;
}
public Node<T> DeQueue() //Remove an element from the queue
{
if (outbox.size == 0)
{
while (inbox.size != 0)
{
outbox.Push(inbox.Pop().data);
}
}
Node<T> temp = new Node<T>();
if (outbox.size != 0)
{
temp = outbox.Pop();
size--;
}
return temp;
}
}
public Node<T> Peek()
{
if (isEmpty())
{
Console.WriteLine("Queue is empty!");
return "No elements";
}
else
{
Console.WriteLine(""Top item is:{0}", Node<T>.Peek());
}
}
public class Node<T>
{
public T data;
public Node<T> link;
}
static void Main(string[] args)
{
Queue<int> q = new Queue<int>();
for (int i = 1; i <= 3; i++)
q.EnQueue(i);
// q.Display();
for (int i = 1; i < 3; i++)
q.DeQueue();
//q.Display();
q.Peek();
//q.Display();
Console.ReadKey();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.