using System;
using System.Collections.Generic;
using System.Text;
namespace link
{
class Program
{
static void Main(string[] args)
{
SLinkList p = new SLinkList();
// p.CreateListHead(); //头插法
p.CreateListTail(); //尾插法
p.PrintList(); //输出全部结点
Console.WriteLine("Length={0}",p.GetLength()); //输出单链表长度
}
}
//********************************************//
//链表类
class SLinkList
{
private SNode start;//单链表的头引用
int length=0;//单链表的长度
//初始化线性表
public SLinkList()
{
start = null;
}
//头插法创建单链表
//public void CreateListHead( )
//{
// int d;
// d = Int32.Parse(Console.ReadLine());
// while (d != -1)
// {
// SNode p = new SNode(d);
// p.Next = start;
// start = p;
// d = Int32.Parse(Console.ReadLine());
// }
//}
//尾插法创建单链表
public void CreateListTail()
{
SNode R = new SNode();
int d;
d = Int32.Parse(Console.ReadLine());
while (d != -1)
{
SNode p = new SNode(d,null);
if (start == null)
start = p;
else
R.Next = p;
R = p;
d = Int32.Parse(Console.ReadLine());
}
}
//输出单链表元素
public void PrintList( )
{
SNode node = start;
while (node != null)
{
Console.WriteLine("{0}", node.Data);
node = node.Next;
}
}
//求单链表的长度
public int GetLength()
{
SNode q = start;
while (q != null)
{
length++;
q = q.Next;
}
return length;
}
}
//*****************************************************//
//结点类
class SNode
{
private int data; //数据域
private SNode next; //引用域
public SNode(int val, SNode p)
{
data = val;
next = p;
}
public SNode(SNode p)
{
next = p;
}
public SNode(int val)
{
data = val;
next = null;
}
public SNode()
{
data = default(int);
next = null;
}
//数据域属性
public int Data
{
get
{
return data;
}
set
{
data = value;
}
}
//引用域属性
public SNode Next
{
get
{
return next;
}
set
{
next = value;
}
}
}
}