Sort LinkList

public static LinkList SortList(LinkList list)
{
Node current = list.HeadNode.Next;
LinkList sortedList = new LinkList();
Node sortedListNewNode;
Node sortedListCurrent;
Node sortedListPre;
while (current != null)
{
//循环sortedList 将current插入合适位置
if (sortedList.HeadNode.Next != null)
{
sortedListPre = sortedList.HeadNode;
sortedListCurrent = sortedList.HeadNode.Next;
while (true)
{
if (current.Value < sortedListCurrent.Value)
{
sortedListNewNode = new Node(current.Value);
sortedListNewNode.Next = sortedListCurrent;
sortedListPre.Next = sortedListNewNode;
break;
}
else
{
sortedListPre = sortedListPre.Next;
sortedListCurrent = sortedListCurrent.Next;
if (sortedListCurrent == null)
{
sortedListPre.Next = new Node(current.Value);
break;
}
}
}
}
else
{
sortedList.HeadNode.Next = new Node(current.Value);
}
//带排序列向后移动
current = current.Next;
}
return sortedList;
}

--------------------华丽分割-----------------------

public static void SortList(LinkList list)
{
bool change = true;
while (change)
{
change = false;
Node prePreNode = list.HeadNode;
Node preNode = list.HeadNode.Next;
Node nextNode = preNode.Next;
while (preNode.Next != null)
{
if (preNode.Value > nextNode.Value)
{
preNode.Next = nextNode.Next;
nextNode.Next = preNode;
prePreNode.Next = nextNode;
change = true;
prePreNode = nextNode;
nextNode = preNode.Next;
}
else
{
prePreNode = prePreNode.Next;
preNode = preNode.Next;
nextNode = nextNode.Next;
}
}
}
}

------------------------------------

public class LinkList
{
public LinkList()
{
this.HeadNode = new Node()
{
Next = null,
Value = 0
};
}
public Node HeadNode;
public override string ToString()
{
StringBuilder sb = new StringBuilder();
Node current = HeadNode.Next;
while (current != null)
{
sb.AppendFormat("{0} ", current.Value);
current = current.Next;
}
return sb.ToString();
}
}

public class Node
{
public Node()
{

}

public Node(int value)
{
this.Value = value;
}

public int Value;
public Node Next;
}

原文地址:https://www.cnblogs.com/fmys/p/7986326.html