C#上机题 - 双向循环链表
2010-09-30 21:00:02 来源:WEB开发网这里使用的是泛型类,他的优势就不讨论了,下面是循环链表类
/// <summary>
/// 双向循环链表
/// </summary>
/// <typeparam name="T"></typeparam>
public class CircleList<T> : IEnumerable<T>
{
private int currentIndex;
private DoubleLinkNode<T> current;
/// <summary>
/// 头节点
/// </summary>
public DoubleLinkNode<T> First { get; private set; }
/// <summary>
/// 尾节点
/// </summary>
public DoubleLinkNode<T> Last { get; private set; }
/// <summary>
/// 节点数
/// </summary>
public int Count { get; private set; }
/// <summary>
/// 索引
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public DoubleLinkNode<T> this[int index]
{
get
{
if (Count - index < index)
{
currentIndex = Count - 1;
current = Last;
while (currentIndex > 0)
{
if (currentIndex == index) break;
currentIndex--;
current = current.Previous;
}
}
else
{
Reset();
while (currentIndex < Count - 1)
{
if (currentIndex == index) break;
currentIndex++;
current = current.Next;
}
}
return current;
}
}
/// <summary>
/// 在尾部添加节点
/// </summary>
/// <param name="node"></param>
public void AddLast(DoubleLinkNode<T> node)
{
if (Last == null) Last = node;
if (First == null) First = node;
Last.Next = node;
node.Previous = Last;
Last = node;
node.Next = First;
First.Previous = node;
Count++;
Last.Next = First;
}
/// <summary>
/// 在尾部添加节点
/// </summary>
/// <param name="item"></param>
public void AddLast(T item)
{
DoubleLinkNode<T> node = new DoubleLinkNode<T>(item);
AddLast(node);
}
/// <summary>
/// 移除节点
/// </summary>
/// <param name="node"></param>
public void Remove(DoubleLinkNode<T> node)
{
node.Previous.Next = node.Next;
node.Next.Previous = node.Previous;
Count--;
}
/// <summary>
/// 移除节点
/// </summary>
/// <param name="item"></param>
public void Remove(T item)
{
DoubleLinkNode<T> node = Find(o => o.Value.Equals(item));
if (node == null) return;
Remove(node);
Count--;
}
/// <summary>
/// 查找节点
/// </summary>
/// <param name="match"></param>
/// <returns></returns>
public DoubleLinkNode<T> Find(Predicate<DoubleLinkNode<T>> match)
{
Reset();
while (currentIndex < Count)
{
if (match(current))
{
return current;
}
currentIndex++;
current = current.Next;
}
return null;
}
public IEnumerator<T> GetEnumerator()
{
Reset();
while (currentIndex < Count)
{
yield return current.Value;
current = current.Next;
currentIndex++;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public override string ToString()
{
string s = string.Empty;
Reset();
while (currentIndex < Count)
{
s += string.Format("Node:{0} NextNode:{1} PreviousNode:{2}\r\n", current, current.Next, current.Previous);
currentIndex++;
current = current.Next;
}
return s;
}
/// <summary>
/// 清除
/// </summary>
public void Clear()
{
Count = 0;
First = null;
Last = null;
}
private void Reset()
{
currentIndex = 0;
current = First;
}
}
- ››循环不间断向上滚动的文本特效代码
- ››循环链表实验
- ››双向链表的排序
- ››双向链表&&堆栈
- ››循环复用DNS实现多服务器的负载均衡
更多精彩
赞助商链接