链表的有序插入的原理:无论什么插入都是万变不离其宗的,只要把握好链表的插入终归是在两个数之间插入新的元素(感觉说了废话)
链表的有序插入要始终考虑到一个问题:插入的位置是在哪里?
有序插入其实就是在插入的基础上加了一个排序的功能。而排序的功能的实现离不开循环。
综上,我们在不断插入元素时需要考虑到是插入的位置在头结点还是中间或者是尾部,再进行排序
方法一
class Node
{
public Node next;
public int data;
public Node(int data)
{
this.data = data;
}
}
class MyLinkedList
{
public int size;//记录元素个数,表长
public Node head;
public Node last;
public MyLinkedList()
{
head = new Node(-1);//构造带有头结点的单链表
}
public void SortInsert2(int data)
{
var p = head;
while (p!=null)
{
if (p.next == null // 这里同时判断两种情况:1、是空链表(只有头结点)2、如果已经比较到最后,但没有比待插入结点大的结点,就在null结点前插入待插入结点
|| data >= p.next.data // 正常判定待插入结点比下一个结点小,就插入在大的结点(下一个结点p.next)前
)
{
var p2 = new Node(data);
p2.next = p.next;
p.next = p2;
return;
}
p = p.next;
}
}
public void print()
{
for (Node p = head.next; p != null; p = p.next)
{
Console.WriteLine(p.data);
}
}
}
class Program
{
static void Main(string[] args)
{
MyLinkedList ll = new MyLinkedList();
ll.SortInsert2(3);
ll.SortInsert2(5);
ll.SortInsert2(4);
ll.SortInsert2(8);
ll.print();
Console.ReadLine();
}
}
方法二
class Node
{
public Node next;
public int data;
public Node(int data)
{
this.data = data;
}
}
class List
{
public Node head;
public List()
{
head = new Node(-1);//头结点
}
public void SortInsert(int data)
{
Node insertNode = new Node(data);
if (head.next == null)
{
head.next = insertNode;
insertNode.next = null;
}
else
{
Node p = head;//p指针指向头结点,方便进行操作
while (p != null)
{
if (p.next != null && data >= p.next.data)
{
insertNode.next = p.next;
p.next = insertNode;
return;
}
else if (p.next == null)
{
insertNode.next = p.next;
p.next = insertNode;
return;
}
p = p.next;//指针指向下下一个元素,p与p.next两个指针一起向后移动
}
}
}
public void print()
{
for (Node p = head.next; p != null; p = p.next)
{
Console.WriteLine(p.data);
}
}
}
方法三
class Node
{
public int data;
public Node next;
public Node(int data)
{
this.data = data;
next = null;
}
}
class MyList
{
private Node head;
public int count;
public MyList()
{
head = new Node(-1);
count = 0;
}
public void Insert(int data)
{
Node insertNdoe = new Node(data);//插入结点
if (count == 0)
{
head.next = insertNdoe;
count++;
return;
}
for (Node p = head.next; ; p = p.next)
{
if (p == head.next && data <= p.data)
{
insertNdoe.next = p;
head.next = insertNdoe;
count++;
return;
}
if (p.next != null && data <= p.next.data)
{
insertNdoe.next = p.next;
p.next = insertNdoe;
count++;
return;
}
else if (p.next == null)
{
insertNdoe.next = p.next;
p.next = insertNdoe;
count++;
return;
}
}
}
public void print()
{
for (Node p = head.next; p != null; p = p.next)
{
Console.WriteLine(p.data);
}
}
}