147. 对链表进行插入排序

自己做
解:设置哨兵

/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode insertionSortList(ListNode head) {ListNode p = head.next;ListNode q = head;ListNode r = new ListNode(0, head); //哨兵head = r;while(p != null){//进行插入if(p.val < q.val){ //需要插入的情况while(r != q){if(r.next.val > p.val){ //在r后插入pq.next = p.next;p.next = r.next;r.next = p;p = q.next;break;}r = r.next;}r = head;}else{ //不需要插入的情况q = p;p = p.next; }}return head.next;}
}
