题目
You have seen many generic-type collections like Lists. When you want to use a List, you can create it for any type like List of int, List of string, List of arrays or …
Your task is easy; you have to create a customized generic class named Loop; (it is a closed loop like a circle to rotate left and right)
It has specific functionalities:
- You can add objects to it. It adds the object to the end of the Loop. The loop can also use collection initializer. (like a List)
- You can rotate it to the Right or Left. So the end and beginning of the loop are changed. I refer the test case to see more details.
- You can ShowFirst or PopOut the first item. Show just return the first item, while PopOut returns the first item while removing it from the loop.
- There is no situation to face empty list. You don’t need to handle any exception.
解题思路
此题需要完成的功能:添加、左右旋转(类似左轮手枪或保险柜锁那种)以及对首个元素的处理
1. 实现添加功能,需要继承System.Collections.IEnumerable,同时写上public System.Collections.IEnumerator GetEnumerator(){ return null; },目的是为了使其可以初始化添加元素(就是数组大括号里面写上元素那种);同时这里的添加指的是往最后一个元素后添加,因此要写成list.AddAfter(end,item);
2. 此题名为Loop,意思即为这个类实例出来的列表是一个首尾相连的数组,里面的元素左移或右移,意味着对开头和结尾的元素影响最大,需要考虑这两者的变化;
3. 此题应该先考虑类的返回类型,这里设定为T,随后考虑存储元素的容器,这里使用的是linkedList(链表)和LinkedListNode(链表节点),这两个类中的属性用法需要注意,基本都会用到;
4. 需要考虑到这个链表一开始为空的情况,此时添加进去的元素既是start又是end;
5. 链表节点存储了该节点的元素value,以及该元素的下一个元素的指针;
代码
using System.Collections.Generic;
public class Loop<T>: System.Collections.IEnumerable
// ,System.Collections.Generic.IEnumerable<T>
{
private LinkedList<T> list;
private LinkedListNode<T> start;
private LinkedListNode<T> end;
public Loop(){
list = new LinkedList<T>();
}
public void Add(T item)
{
if(end == null){
this.list.AddLast(item);
this.start = list.First;
this.end = list.Last;
}
else{
this.list.AddAfter(end, item);
this.end = this.end.Next;
}
}
public void Rigth()
{
if(this.start.Previous != null){
this.start = this.start.Previous;
}
else{
this.start = this.list.Last;
}
if(this.end.Previous != null){
this.end = this.end.Previous;
}
else {
this.end = this.list.Last;
}
}
public void Left()
{
if(this.start.Next != null){
this.start = this.start.Next;
}
else{
this.start = this.list.First;
}
if(this.end.Next != null){
this.end = this.end.Next;
}
else {
this.end = this.list.First;
}
}
public T PopOut()
{
var val = this.start.Value;
var oldStart = this.start;
if(this.start.Next != null){
this.start = this.start.Next;
}
else{
this.start = this.list.First;
}
this.list.Remove(oldStart);
return val;
}
public T ShowFirst()
{
return this.start.Value;
}
public System.Collections.IEnumerator GetEnumerator(){ return null; }
}
参考资料
- linkedList(链表)https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.linkedlist-1?view=netframework-4.7.2
- LinkedListNode(链表节点)https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.linkedlistnode-1?view=netframework-4.7.2
- IEnumerable Interface(接口)
https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.ienumerable?view=netframework-4.7.2