forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_147.java
58 lines (54 loc) · 1.46 KB
/
_147.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.fishercoder.solutions;
import com.fishercoder.common.classes.ListNode;
import java.util.ArrayList;
import java.util.List;
/**
* 147. Insertion Sort List
*
* Sort a linked list using insertion sort.
*
* Algorithm of Insertion Sort:
*
* Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
* At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
* It repeats until no input elements remain.
*
*
* 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
*/
public class _147 {
public static class Solution1 {
public ListNode insertionSortList(ListNode head) {
ListNode temp = head;
List<Integer> list = new ArrayList<>();
while (temp != null) {
list.add(temp.val);
temp = temp.next;
}
Integer[] nums = list.toArray(new Integer[list.size()]);
for (int i = 1; i < list.size(); i++) {
for (int j = i - 1; j >= 0; j--) {
if (nums[j] > nums[j + 1]) {
int tempNum = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tempNum;
}
}
}
ListNode newHead = head;
for (int i = 0; i < nums.length; i++) {
newHead.val = nums[i];
newHead = newHead.next;
}
return head;
}
}
}