Day 1.19
排序链表
题目
思路(1)
把head
节点值依次取出,放入数组a[]
中,再对a[]
排序,最后依次取出a[]
的元素拼接成新链表
class Solution {
public ListNode sortList(ListNode head) {
ListNode n = new ListNode(1),h = n;
if(head == null)
return null;
int a[] = new int[50000];
int i = 0;
while(head != null){
a[i++] = head.val;
head = head.next;
}
int b[] = new int[i];
int s = 0;
while(s<i){
b[s] = a[s];
s++;
}
for(int j = b.length-1; j > 0; j--){
for(int k = 0; k < j; k++){
if(b[k] > b[k+1]){
int temp = b[k];
b[k] = b[k+1];
b[k+1] = temp;
}
}
}
for(int m = 0;m < b.length;m++){
n.next = new ListNode(b[m]);
n = n.next;
}
return h.next;
}
}
思路(2)(归并)
原理:
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
// 归并排序
// 递归解法
if(head == null || head.next == null) {
return head;
}
ListNode midNode = findMidNode(head);
// 右边链表的头结点
ListNode rightHead = midNode.next;
// 注意:需要维护链表 --> 断开左右链表,变成两个链表
midNode.next = null;
// 对左边的链表进行排序
ListNode left = sortList(head);
// 对右边的链表进行排序
ListNode right = sortList(rightHead);
// 合并链表
return merge(left,right);
}
public ListNode findMidNode(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode slow = head;
ListNode fast = head.next.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return fast != null ? slow.next : slow;
}
public ListNode merge(ListNode left,ListNode right) {
ListNode dummyNode = new ListNode(0);
ListNode current = dummyNode;
while(left != null && right != null) {
if(left.val < right.val) {
current.next = left;
left = left.next;
}else {
current.next = right;
right = right.next;
}
current = current.next;
}
current.next = left != null ? left : right;
return dummyNode.next;
}
}