题目:
我的解法:
新建一个链表,遍历原来的链表,为每一个结点寻找在新链表中的插入位置,最终返回新链表。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode insert_node = new ListNode(Integer.MIN_VALUE);
ListNode no_insert_node = head;
while(no_insert_node!=null){
ListNode temp = no_insert_node.next;
no_insert_node.next = null;
insert(insert_node, no_insert_node);
no_insert_node = temp;
}
return insert_node.next;
}
public void insert(ListNode m, ListNode n){
ListNode in = m;
while(in!=null && in.next!=null){
if(in.val<=n.val && in.next.val>=n.val){
ListNode temp = in.next;
in.next = n;
in.next.next = temp;
return;
}
in = in.next;
}
if(in.val<=n.val){
in.next = n;
}
return;
}
}
官方题解:
class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null) {
return head;
}
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode lastSorted = head, curr = head.next;
while (curr != null) {
if (lastSorted.val <= curr.val) {
lastSorted = lastSorted.next;
} else {
ListNode prev = dummyHead;
while (prev.next.val <= curr.val) {
prev = prev.next;
}
lastSorted.next = curr.next;
curr.next = prev.next;
prev.next = curr;
}
curr = lastSorted.next;
}
return dummyHead.next;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/insertion-sort-list/solution/dui-lian-biao-jin-xing-cha-ru-pai-xu-by-leetcode-s/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。