版权声明: https://blog.csdn.net/qq_38386316/article/details/83186821
题目描述:
对链表进行插入排序。
插入排序的动画演示如上。从第一个元素开始,该链表可以被认为已经部分排序(用黑色表示)。每次迭代时,从输入数据中移除一个元素,并原地将其插入已拍好的链表中。
示例 1
- 输入:
- 输出:
示例 2
- 输入:
- 输出:
思路
利用插入排序的思想,每次移动一个元素,至已排序的链表中合适的位置。直到数据遍历完为止。重复操作。
代码
class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode cur = new ListNode(-1);
ListNode dummpy = cur;
ListNode prev = head;
while(head != null){
ListNode cur2 = cur;
prev = head;
head = head.next;
while(cur2.next != null && cur2.next.val <= prev.val) {
cur2 = cur2.next;
//System.out.println(cur2.val);
}
//cur2.next = prev;
prev.next = cur2.next;
cur2.next = prev;
}
return dummpy.next;
}
}
复杂度分析
- 时间复杂度:
- 空间复杂度:
完整代码
package leetcode147;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created by 张超帅 on 2018/10/19.
*/
class ListNode {
int val;
ListNode next;
ListNode(int x){this.val = x;}
}
class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode cur = new ListNode(-1);
ListNode dummpy = cur;
ListNode prev = head;
while(head != null){
ListNode cur2 = cur;
prev = head;
head = head.next;
while(cur2.next != null && cur2.next.val <= prev.val) {
cur2 = cur2.next;
}
prev.next = cur2.next;
cur2.next = prev;
}
return dummpy.next;
}
}
public class leetcode147 {
public static int[] stringToArrays(String input){
input = input.trim();
input = input.substring(1, input.length() - 1);
if(input == null) {
return new int[0];
}
String[] parts = input.split(",");
int[] res = new int[parts.length];
for(int i = 0; i < parts.length; i ++) {
res[i] = Integer.parseInt(parts[i]);
}
return res;
}
public static ListNode stringToListNode(String input) {
int[] nodes = stringToArrays( input);
ListNode dummpy = new ListNode(-1);
ListNode cur = dummpy;
for(int node : nodes){
cur.next = new ListNode(node);
cur = cur.next;
}
return dummpy.next;
}
public static String listnodeToString(ListNode head){
if(head == null){
return "[]";
}
String res = "";
while(head != null){
res += head.val + ", ";
head = head.next;
}
return "[" + res.substring(0, res.length() - 2) + "]";
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line = in.readLine()) != null) {
ListNode head = stringToListNode(line);
ListNode ret = new Solution().insertionSortList(head);
System.out.println(listnodeToString(ret));
}
}
}