Sort a linked list using insertion sort.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
if(head==null) {
return head;
}
ListNode pre = head;
ListNode cur = head.next;
ListNode newHead = head;
while(true) {
if(cur==null) {
break;
}
ListNode tmp = cur;
ListNode tmpPre = pre;
pre = cur;
cur = cur.next;
if(tmp.val<newHead.val) {
tmpPre.next = tmp.next;
tmp.next = newHead;
newHead = tmp;
pre = tmpPre;
} else if(tmp.val<tmpPre.val){
ListNode tmp2 = newHead;
while(tmp2.next!=tmp) {
if(tmp.val<tmp2.next.val) {
tmpPre.next = tmp.next;
tmp.next = tmp2.next;
tmp2.next = tmp;
break;
}
tmp2 = tmp2.next;
}
pre = tmpPre;
}
}
return newHead;
}
}
public class Solution {
public ListNode insertionSortList(ListNode head) {
if(head==null || head.next==null) return head;
ListNode dummy = new ListNode(Integer.MIN_VALUE);
ListNode p1 = head;
while(p1!=null) {
ListNode p2 = p1.next;
ListNode p0 = dummy;
boolean insert = false;
while(p0.next!=null) {
if(p1.val<p0.next.val) {
ListNode tmp = p0.next;
p0.next = p1;
p1.next = tmp;
insert = true;
break;
}
p0 = p0.next;
}
if(!insert) {
p0.next = p1;
p1.next = null;
}
p1 = p2;
}
return dummy.next;
}
}
====================
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(0);
ListNode p = head;
while (p != null) {
ListNode nextP = p.next;
ListNode from = dummy;
while (from.next != null && p.val > from.next.val) {
from = from.next;
}
ListNode p2 = from.next;
from.next = p;
p.next = p2;
p = nextP;
}
return dummy.next;
}
}
没有评论:
发表评论