题目
https://leetcode-cn.com/problems/insertion-sort-list/description/
代码
/*
* @lc app=leetcode.cn id=147 lang=java
*
* [147] 对链表进行插入排序
*/
// @lc code=start
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode insertionSortList(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode result = new ListNode(head.val);
head = head.next;
while(head!=null){
result=insertSort(result, head.val);
head=head.next;
}
return result;
}
private ListNode insertSort(ListNode result, int val){
ListNode p =result;
ListNode pre = result;
int flag=0;
while(p!=null){
if(p.val > val){
ListNode listNode = new ListNode(val);
if(flag==0){
listNode.next=result;
return listNode;
}else{
pre.next=listNode;
listNode.next=p;
return result;
}
}else{
if(flag==0){
p=p.next;
flag=1;
}else{
p=p.next;
pre=pre.next;
}
}
}
ListNode tailNode = new ListNode(val);
pre.next=tailNode;
return result;
}
}
// @lc code=end