using System;
namespace List
{
public class ListNode
{
public ListNode(int value) => Value = value;
public ListNode Previous { get; set; }
public ListNode Next { get; set; }
public int Value { get; set; }
}
}
維護 Head、Tail、Current 三個指標,支援常見操作:
using System;
namespace List
{
public class Clist
{
private ListNode head, tail, current;
private int count;
public Clist()
{
head = tail = current = null;
count = 0;
}
public bool IsEmpty => count == 0;
public bool IsAtHead => current == head;
public bool IsAtTail => current == tail;
public int Count => count;
public int CurrentValue => current?.Value ?? 0;
// 尾部新增
public void Append(int value)
{
var node = new ListNode(value);
if (IsEmpty)
{
head = tail = node;
}
else
{
tail.Next = node;
node.Previous = tail;
tail = node;
}
current = node;
count++;
}
// 刪除目前節點
public void Delete()
{
if (IsEmpty) return;
if (IsAtHead)
{
head = current.Next;
current = head;
}
else if (IsAtTail)
{
tail = current.Previous;
current = tail;
}
else
{
current.Previous.Next = current.Next;
current = current.Previous;
}
count--;
}
// 導航
public void MoveNext() => current = current?.Next ?? current;
public void MovePrevious() => current = current?.Previous ?? current;
public void MoveFirst() => current = head;
public void MoveLast() => current = tail;
// 目前位置前插入
public void Insert(int value)
{
var node = new ListNode(value);
if (IsEmpty) { Append(value); return; }
if (IsAtHead)
{
node.Next = head;
head.Previous = node;
head = node;
}
else
{
node.Next = current;
node.Previous = current.Previous;
current.Previous.Next = node;
current.Previous = node;
}
current = node;
count++;
}
// 升序插入
public void InsertAscending(int value)
{
if (IsEmpty) { Append(value); return; }
MoveFirst();
if (value < CurrentValue) { Insert(value); return; }
while (true)
{
if (value < CurrentValue) { Insert(value); break; }
if (IsAtTail) { Append(value); break; }
MoveNext();
}
}
// 降序插入
public void InsertDescending(int value)
{
if (IsEmpty) { Append(value); return; }
MoveFirst();
if (value > CurrentValue) { Insert(value); return; }
while (true)
{
if (value > CurrentValue) { Insert(value); break; }
if (IsAtTail) { Append(value); break; }
MoveNext();
}
}
public void Clear()
{
MoveFirst();
while (!IsEmpty) Delete();
}
}
}
Previous/Next 支援雙向遍歷與 O(1) 刪除目前節點。Current 指標配合 MoveNext/Previous/First/Last 進行遍歷,Insert/Delete 作用於目前位置。NullReferenceException。InsertAscending/Descending 從頭掃描至適當位置再插入,時間複雜度 O(n)。IEnumerable<int>、ICollection<int>,支援 foreach、LINQ。Nullable<int> 或 int? 表示無目前值,而非回傳 0。LinkedList<T> (BCL 內建) 或自訂泛型 DoublyLinkedList<T> 取代 int 專用版本。this[int index] 支援隨機存取 (O(n))。