using System;
using System.Collections.Generic;
using System.Text;
namespace List
{
class Node
{
public Node()
{
}
public Node(int data)
{
this.data = data;
this.next = null;
}
public int Data
{
set
{
data = value;
}
get
{
return data;
}
}
public Node Next
{
set
{
next = value;
}
get
{
return next;
}
}
private int data;
private Node next;
}
class List
{
public List()
{
head = null;
}
//按照從小到大的順序插入
public void Insert(int data)
{
Node node = new Node(data);//創建節點
//如果鏈表為空
if (ReferenceEquals(head, null))
{
head = node;
return;
}
//如果鏈表不為空
Node cur = head;
Node prev = null;
while (!ReferenceEquals(cur, null))
{
if (data < cur.Data)
{
if (ReferenceEquals(prev, null)) //如果節點node要插入在第一個節點之前
{
head = node;
head.Next = cur;
}
else
{
prev.Next = node;
node.Next = cur;
}
return;
}
prev = cur;
cur = cur.Next;
}
//如果節點node要插入在最後一個節點之後
prev.Next = node;
}
//刪除鏈表中節點值為data的節點
public void Delete(int data)
{
Node node = new Node(data);//創建節點
if (ReferenceEquals(head, null))//如果鏈表為空,直接返回
{
return;
}
Node cur = head;
Node prev = null;
while (!ReferenceEquals(cur, null))//循環,直到最後一個節點的下一個節點
{
if (cur.Data == data)
{
if (ReferenceEquals(prev, null))//要刪除的節點是第一個節點
{
head = cur.Next;
}
else //否則
{
prev.Next = cur.Next;
}
return;
}
//指針後移
prev = cur;
cur = cur.Next;
}
}
public void Disply()
{
Node cur = head;
while (!ReferenceEquals(cur, null))
{
Console.Write(cur.Data);
if (!ReferenceEquals(cur.Next, null))
{
Console.Write("->");
}
cur = cur.Next;
}
Console.WriteLine();
}
//這個方法重寫了object類的ToString()方法,用於輸出
//public override string ToString()
//{
// StringBuilder str = null;
// Node cur = head;
// while (!ReferenceEquals(cur,null))
// {
// str.Append(cur.Data);
// if (!ReferenceEquals(cur.Next, null))
// {
// str.Append("->");
// }
// cur = cur.Next;
// }
// string str2 = str.ToString();
// return str2;
//}
private Node head;
}
}