C#让链表实现已排序链表
时间: 2023-11-30 07:41:39 浏览: 84
以下是C#中让链表实现已排序链表的方法:
1.使用LinkedList.Sort()方法进行排序
```csharp
LinkedList<int> list = new LinkedList<int>();
list.AddLast(3);
list.AddLast(1);
list.AddLast(2);
list.Sort();
foreach (int i in list)
{
Console.WriteLine(i);
}
```
2.手动插入排序
```csharp
LinkedList<int> list = new LinkedList<int>();
list.AddLast(3);
list.AddLast(1);
list.AddLast(2);
LinkedListNode<int> current = list.First.Next;
while (current != null)
{
LinkedListNode<int> next = current.Next;
LinkedListNode<int> temp = current.Previous;
while (temp != null && temp.Value > current.Value)
{
temp = temp.Previous;
}
if (temp == null)
{
list.Remove(current);
list.AddFirst(current);
}
else if (temp.Next != current)
{
list.Remove(current);
list.AddAfter(temp, current);
}
current = next;
}
foreach (int i in list)
{
Console.WriteLine(i);
}
```
3.使用LINQ进行排序
```csharp
LinkedList<int> list = new LinkedList<int>();
list.AddLast(3);
list.AddLast(1);
list.AddLast(2);
var sortedList = list.OrderBy(x => x);
foreach (int i in sortedList)
{
Console.WriteLine(i);
}
```
阅读全文