Insertion sort on linked list

The topic is above leetcode, and the contents of the topic are as follows:

 

 

Insertion sort on the linked list.

The animation of insertion sort is shown above. Starting from the first element, the linked list can be considered partially sorted (indicated in black).
At each iteration, an element (shown in red) is removed from the input data and inserted into the sorted linked list in place.

 

Insertion sort algorithm:

  1. Insertion sort is iterative, moving only one element at a time, until all elements can form an ordered output list.
  2. In each iteration, insertion sort removes only one element to be sorted from the input data, finds its proper position in the sequence, and inserts it.
  3. Repeat until all input data is inserted.

 

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5 


Here is my code:
 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     public ListNode insertionSortList(ListNode head) {
11         ArrayList<Integer> arr = new ArrayList<Integer>();
12         if (head == null) return head;
13         while (head != null)
 14          { // Store the linked list in the array 
15              arr.add(head.val);
 16              head = head.next;
 17          }
 18      
19          // Sort the array with insertion sort 
20          for ( int i = 1; i < arr.size(); i++ )
 21          {
 22              for ( int j = i; j > 0 && (arr.get(j) < arr.get(j - 1)); j-- )
 23              {
 24                  int temp = arr.get(j);
 25                  arr.set(j, arr.get(j-1 ));
 26                 arr.set(j-1, temp);
27             }
28         }
29     
30         //将数组转换成链表
31         ListNode first = new ListNode(arr.get(0));
32         ListNode temp = first;
33         for (int i = 1; i < arr.size(); i++)
34         {
35             ListNode node = new ListNode(arr.get(i));
36             temp.next = node;
37             temp = node;
38         }
39     
40         return first;
41     }
42 }

Although it's a bit out of control, this method should be pretty good, right? I admire the method of converting an array into a linked list that I came up with.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325276843&siteId=291194637