您的位置:首页 > 编程语言 > C#

c#中简单链表的实现(非泛型)

2008-12-06 16:09 429 查看
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections;

namespace 泛型

{

//简单链表的实现,单向

class 泛型类

{

public static void Main()

{

LinkedList list = new LinkedList();

list.AddLast("500");

list.AddLast("400");

list.AddLast("300");

list.AddLast("200");

foreach (string i in list)

{

Console.WriteLine(i);

}

Console.ReadLine();

}

}

//结点类

class LinkedListNode

{

//项目值

private object value;

private LinkedListNode next;

private LinkedListNode prev;

public LinkedListNode( object value )

{

this.value = value;

}

public object Value

{

//只读属性

get

{

return this.value;

}

}

//下一个

public LinkedListNode Next

{

get { return next; }

set { next = value; }

}

//上一个

public LinkedListNode Prev

{

get { return prev; }

set { prev = value; }

}

}

class LinkedList : IEnumerable

{

//第一个

private LinkedListNode first;

internal LinkedListNode First

{

get { return first; }

set { first = value; }

}

//最后一个

private LinkedListNode last;

internal LinkedListNode Last

{

get { return last; }

set { last = value; }

}

//从后面插入

public LinkedListNode AddLast(object node)

{

LinkedListNode newNode = new LinkedListNode( node );

if (first == null)

{

//Last的引用一直要更新

first = newNode;

last = first;

}

else

{

//把当前最后一个节点的下一个节点的引用 指向新对象

last.Next = newNode;

//更新最后一个节点

last = newNode;

}

return newNode;

}

#region IEnumerable 成员

public IEnumerator GetEnumerator()

{

LinkedListNode current = first;

while (current != null)

{

yield return current.Value;

//新引用指向下一个节点的地址

current = current.Next;

}

}

#endregion

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: