ToB企服应用市场:ToB评测及商务社交产业平台
标题:
C#中的栈与队列/练习
[打印本页]
作者:
农妇山泉一亩田
时间:
2023-11-16 15:39
标题:
C#中的栈与队列/练习
C#栈和队列的实现
用双向链表实现一个队列
public class DoubleNode
{
public int Value;
public DoubleNode pre;
public DoubleNode next;
public DoubleNode(int value)
{
this.Value = value;
this.pre=null;
this.next=null;
}
}
public class MyQueue//使用双向链表实现队列
{
public DoubleNode head;
public DoubleNode tail;
public void AddFromHead(DoubleNode node)//从队头插入节点
{
if(head == null)
{
head = node;
tail = node;
}
else
{
node.next = head;
head.pre = node;
head = node;
}
}
public void AddFromTail(DoubleNode node)//从队尾插入节点
{
if(tail == null)
{
tail = node;
head=node;
}
else
{
node.pre = tail;
tail.next = node;
tail = node;
}
}
public DoubleNode PopFromHead()//从队头弹出节点
{
if (head == null) return null;
DoubleNode res = head;
if (head==tail)
{
head=null;
tail=null;
}
else
{
head = head.next;
res.next=null;
head.pre=null;
}
return res;
}
public DoubleNode PopFromTail()//从队尾弹出节点
{
if (tail==null) return null;
DoubleNode res=tail;
if (head==tail)
{
head=null;
tail=null;
}
else
{
tail=tail.pre;
res.pre=null;
tail.next=null;
}
return res;
}
}
复制代码
使用双向链表实现栈
public class MyStack//使用双向链表实现栈
{
public DoubleNode Head;
public DoubleNode Tail;
public void Push(int value)
{
DoubleNode temp = new DoubleNode(value);
if (Head == null)
{
Head = temp;
Tail= temp;
}
else
{
temp.next= Head;
Head.pre = temp;
Head = temp;
}
}
public DoubleNode Pop()
{
if (Head == null) return null;
DoubleNode res = Head;
if (Head == Tail)
{
Head = null;
Tail = null;
return res;
}
Head = Head.next;
res.next = null;
Head.pre = null;
return res;
}
public DoubleNode Peek()
{
if (Head == null) return null;
return Head;
}
}
复制代码
使用数组实现固定最大长度的栈和队列
public class MyStack1//使用数组实现固定最大长度的栈,暂定为L
{
public int[]nums;
public int index;
public int limit;
public MyStack1(int L)
{
limit = L;
nums= new int[limit];
index=0;
}
public void Push(int n)
{
if (index<limit)
nums[index++] = n;
else
Console.WriteLine("栈已满");
}
public int Pop()
{
int res = nums[--index];
return res;
}
public int Peek()
{
return nums[index-1];
}
}
public class MyQueue1//使用数组实现固定最大长度的队列,暂定为L
{
public int[] nums;
public int headIndex;
public int tailIndex;
public int size;
public int limit;
public MyQueue1(int L)
{
limit = L;
nums=new int[limit];
size=0;
headIndex=0;
tailIndex=0;
}
public int NextIndex(int i)
{
return i<=limit-1? i+1:0;
}
public void Push(int n)
{
if(size==limit)
{
Console.WriteLine("队列已经满了");
return;
}
size++;
nums[tailIndex] = n;
tailIndex=NextIndex(tailIndex);
}
public int Pop()
{
if (size==0)
{
throw new Exception("队列空了");
}
size--;
int res = nums[headIndex];
headIndex=NextIndex(headIndex);
return res;
}
}
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/)
Powered by Discuz! X3.4