C#队列(链表实现)
明白了C#来实现链表的话,本篇文章就变得非常简单了
如果还没有明白如何使用C#来实现链表的话建议看我之前的博客:C#实现链表的传送门
如果不明白什么是队列:C#队列的传送门
链表的话需要一个结点类(Node)
队列的话自然需要一个队列的类(MyQueue)
Node
class Node<T>
{
public T item;
public Node<T> next;
public Node(T item)
{
this.item = item;
this.next = null;
}
}
MyQueue
class myQueue<T>
{
private Node<T> first;
private int count=0;
public int Count
{
get { return this.count; }
set { this.count = value; }
}
public void EnQueue(T t)
{
Count++;
Node<T> node = new Node<T>(t);
if (first == null)
{
first = node;
}
else
{
Node<T> tmp_node = first;
while (tmp_node.next!=null)
{
tmp_node = tmp_node.next;
}
tmp_node.next = node;
}
}
public T DeQueue()
{
if (first == null)
{
throw new Exception("队列为空!!!");
}
else
{
T item = first.item;
first = first.next;
Count--;
return item;
}
}
}
测试的代码
class Program
{
static void Main(string[] args)
{
myQueue<string> myQueue = new myQueue<string>();
myQueue.EnQueue("这是第一条string");
myQueue.EnQueue("这是第二条string");
myQueue.EnQueue("这是第三条string");
myQueue.EnQueue("这是第四条string");
myQueue.EnQueue("这是第五条string");
myQueue.EnQueue("这是第六条string");
while (myQueue.Count!=0)
{
Console.WriteLine(myQueue.DeQueue());
}
Console.ReadKey();
}
}
最后是完整代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp19
{
class Program
{
static void Main(string[] args)
{
myQueue<string> myQueue = new myQueue<string>();
myQueue.EnQueue("这是第一条string");
myQueue.EnQueue("这是第二条string");
myQueue.EnQueue("这是第三条string");
myQueue.EnQueue("这是第四条string");
myQueue.EnQueue("这是第五条string");
myQueue.EnQueue("这是第六条string");
while (myQueue.Count!=0)
{
Console.WriteLine(myQueue.DeQueue());
}
Console.ReadKey();
}
}
class myQueue<T>
{
private Node<T> first;
private int count=0;
public int Count
{
get { return this.count; }
set { this.count = value; }
}
public void EnQueue(T t)
{
Count++;
Node<T> node = new Node<T>(t);
if (first == null)
{
first = node;
}
else
{
Node<T> tmp_node = first;
while (tmp_node.next!=null)
{
tmp_node = tmp_node.next;
}
tmp_node.next = node;
}
}
public T DeQueue()
{
if (first == null)
{
throw new Exception("队列为空!!!");
}
else
{
T item = first.item;
first = first.next;
Count--;
return item;
}
}
}
class Node<T>
{
public T item;
public Node<T> next;
public Node(T item)
{
this.item = item;
this.next = null;
}
}
}