c#实现链队列(队列)

本文介绍使用单链表实现队列的方法,包括队列的基本操作如入队、出队等,并通过设置队尾指针优化了尾部操作的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用单链表实现队列。

front和rear分别表示队列的队头结点和队尾结点。其实并没有必要设置队尾结点这一属性,比如,在实现单链表的时候,并没有加入一个rear的属性,但是加入rear属性的好处在于,避免每次查到尾部元素或者在尾部添加新的元素时,遍历一遍所有的结点,因而单链表的实现实际上也可以做出相同的改进。本质上属于以空间换时间的策略。

队列接口:

//队列接口 interface IQueueDs<T> { int GetLength(); bool IsEmpty(); bool IsFull(); void In(T t); T Out(); T GetFront(); }

链队列的结点类:

//链队列的结点类 class Node<T> { private T tVal; private Node<T> nNext; public T Val { get { return this.tVal; } set { this.tVal = value; } } public Node<T> Next { get { return this.nNext; } set { this.nNext = value; } } public Node() { this.tVal = default(T); this.nNext = null; } public Node(T t) { this.tVal = t; this.nNext = null; } }

链队列类:

//链队列类 class LinkedQueue<T>:IQueueDs<T> { private Node<T> nFront; private Node<T> nRear;//以空间换时间的策略 private int intNum; public Node<T> Front { get { return this.nFront; } set { this.nFront = value; } } public Node<T> Rear { get { return this.nRear; } set { this.nRear = value; } } public int Num { get { return this.intNum; } set { this.intNum = value; } } public LinkedQueue() { this.nFront = null; this.nRear = null; this.intNum = 0; } public LinkedQueue(T t) { Node<T> node = new Node<T>(t); this.nFront = node; this.nRear = node; this.intNum = 1; } #region IQueueDs<T> 成员 public int GetLength() { return this.intNum; } public bool IsEmpty() { return this.intNum == 0; } public bool IsFull() { Console.WriteLine("No limit for LinkedQueue!"); return false; } public void In(T t) { Node<T> node = new Node<T>(t); if (this.IsEmpty()) { this.nFront = node; this.nRear = node; this.intNum++; return; } this.nRear.Next = node; this.nRear = node; this.intNum++; } public T Out() { if (this.IsEmpty()) { Console.WriteLine("No more elements!"); return default(T); } else { Node<T> node = this.nFront; this.nFront = node.Next; this.intNum--; return node.Val; } } public T GetFront() { if (!this.IsEmpty()) { return this.nFront.Val; } else { Console.WriteLine("The queue has no elements!"); return default(T); } } #endregion }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值