insertion sort list

来源:互联网 发布:知乎 中国铁路 非洲 编辑:程序博客网 时间:2024/05/03 23:18
public class Insert2 {


/**
* @param args
*/
public static ListNode insertionSortList(ListNode head) {
// q是外层循环,p是内层循环
if(head==null||head.next==null){
return head;
}
ListNode before = new ListNode(-1);

while (head != null) {
ListNode q = head;
head = head.next;

ListNode p=before;
while (p.next != null && p.next.val < q.val) {
p = p.next;
}
if (p.next == null) {
p.next = q;
q.next = null;
} else {
q.next = p.next;
p.next = q;
}
}
return before.next;


}
public static void main(String[] args) {
// TODO Auto-generated method stub
ListNode head = new ListNode(4);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(6);
ListNode n4 = new ListNode(3);
ListNode n5 = new ListNode(1);
head.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
n5.next = null;
// InsertionSortList kInsertionSortList = new InsertionSortList();
ListNode ret = insertionSortList(head);
while (ret != null) {
System.out.println(ret.val);
ret = ret.next;
}
}


}

创建一个新的头结点before,从head中挨个往before 中添加。head指针用于挨个遍历原链表,并将各个节点给q,p节点用于与q进行比较,使得q可以插入在before中合适的位置。

0 0