上数据结构课,老师布置了作业----操作链表,但我们学的是用C语言实现数据结构,学C#也已经快1年了,就试着写了这个东东,大家提提意见把!
using System;
namespace LinkList
{
/// <summary>
 
/// LinkList 的摘要说明。
 
/// </summary>

 public class LNode   //节点类
 {
  
public LNode(int DataValue)  //构造函数
  {
   Data 
= DataValue;
  }

  
public int Data;  //节点数据,头节点中该值记录链表长度
  public LNode Next;  //节点指针。
 }

 
public class LinkList  //链表操作
 {
  
public LinkList()  //构造函数
  {
   Head 
= null;
   Tail 
= null;
  }

  
private static LNode Head;  //定义头指针
  private static LNode Tail;  //定义尾指针
  private static LNode Current; //定义当前指针
  public static void CreateList() //初始化链表。
  {
   Head 
= new LNode(0); //初始化头节点。
   Head.Next = null;
   Tail 
= Head;
   Current 
= Head;
  }

  
public static void Add(int DataValue)  //在链表结尾添加节点。
  {
   LNode NewNode 
= new LNode(DataValue);  //创建新节点。
   Tail.Next = NewNode;
   Tail 
= NewNode;
   Current 
= NewNode;
   Head.Data
++;
  }

  
public static int GetLength()  //使用方法获取链表长度(方法一)
  {
   
int Count = 0;
   Current 
= Head;
   
while(Current != Tail)
   
{
    Current 
= Current.Next;
    Count
++;
   }

   
return Count;
  }

  
public static int Length   //使用属性获取链表长度(方法二)
  {
   
get
   
{
    
return Head.Data;
   }

  }

  
public static void ShowList()   //显示链表
  {
   Current 
= Head;
   
while(Current != Tail)
   
{
    Console.Write(
"{0}-->",Current.Next.Data);
    Current 
= Current.Next;
   }

  }

  
public static void Main()
  
{
   CreateList();
   Console.WriteLine(
"请数据数字,输入q结束。");
   
string Value;
   
while((Value = Console.ReadLine()) != "q")
   
{
    
int MyValue = Convert.ToInt32(Value);
    Add(MyValue);
   }

   ShowList();
   Console.WriteLine(
"你所需要的链表的长度为{0}",GetLength().ToString());
   Console.WriteLine(
"你所需要的链表的长度为{0}",Length.ToString());
   Console.ReadLine();
  }

 }

}

posted on 2004-12-04 16:38  王喆  阅读(1730)  评论(8编辑  收藏  举报