目录
[2.定义链表类,并实现Append、Print、MoveFirst、 Insert](#2.定义链表类,并实现Append、Print、MoveFirst、 Insert)
1.定义一个泛型节点类并自动属性
cs
/// <summary>
/// 定义泛型节点类
/// </summary>
/// <typeparam name="T">泛型运算符</typeparam>
/// <param name="value">泛型参数</param>
public class ListNode<T>(T value)
{
public T Object { get; set; } = value;
public ListNode<T>? Next { get; set; }
public ListNode<T>? Previous { get; set; }
}
2.定义链表类,并实现Append、Print、MoveFirst、 Insert
cs
/// <summary>
/// 定义链表类
/// </summary>
public class LinkedList
{
private ListNode<int>? _head;
private ListNode<int>? _tail;
private ListNode<int>? _current;
public ListNode<int>? Current { get => _current; set => _current = value; }
/// <summary>
/// 追加节点到Append方法
/// </summary>
/// <param name="value"></param>
public void Append(int value)
{
var newNode = new ListNode<int>(value);
if (_head == null)
{
_head = newNode;
_tail = newNode;
}
else
{
_tail!.Next = newNode;
newNode.Previous = _tail;
_tail = newNode;
}
}
/// <summary>
/// 输出各节点
/// </summary>
public void Print()
{
var current = _head;
while (current != null)
{
Console.WriteLine(current.Object);
current = current.Next;
}
}
/// <summary>
///移动指针到链表头
/// </summary>
public void MoveFirst()
{
if (_head != null)
{
_current = _head;
}
}
/// <summary>
/// 在当前节点后面插入新数据
/// </summary>
/// <param name="value">待插入的数据</param>
public void Insert(int value)
{
// 创建一个新的节点
var newNode = new ListNode<int>(value);
// 如果链表为空,将新节点设置为头节点
if (_head == null)
{
_head = newNode;
_current = newNode;
return;
}
// 找到当前节点
var current = _current;
if (current == null)
{
//current = _head;
_current = _head;
while (_current.Next != null)
{
_current = _current.Next;
}
current = _current;
}
// 在当前位置插入新节点
newNode.Next = current.Next;
newNode.Previous = current;
current.Next = newNode;
_current = newNode;
}
3.Main方法
cs
class Program
{
static void Main(string[] args)
{
ArgumentNullException.ThrowIfNull(args);
var linkedList = new LinkedList();
linkedList.Append(5);
linkedList.Append(2);
linkedList.Append(8);
linkedList.Append(1);
linkedList.Print();
Console.WriteLine("*初始化数据*");
linkedList.MoveFirst();
linkedList.Insert(3);
linkedList.Print();
Console.WriteLine("*头结点后插入3*");
}
}
运行结果:
cs
//运行结果:
/*
5
2
8
1
*初始化数据*
5
3
2
8
1
*头结点后插入3*
*/