/**
* jh
* 2019年04月24日 10:59
*/
public class ListSort {
static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
//插入排序
public static ListNode insertionSortList(ListNode head) {
if (head == null) {
return head;
}
ListNode rest = head.next;
head.next = null;
while (rest != null) {
ListNode cur = head;
ListNode current = rest;
rest = rest.next;
//找到第一个大于rest的节点
ListNode pre = null;
while (cur != null) {
if (cur.val > current.val) {
break;
}
pre = cur;
cur = cur.next;
}
if (pre == null) {
//头结点大于当前节点,替换头结点
current.next = head;
head = current;
} else if (cur == null) {
//已经遍历到尾部,还没有找到大于当前节点
pre.next = current;
//注意尾节点的next为null
current.next = null;
} else {
//正常插入
pre.next = current;
current.next = cur;
}
}
return head;
}
//归并排序
public static ListNode mergeSort(ListNode head){
if(head == null || head.next ==null){
return head;
}
//选取中间节点
ListNode mid = getMid(head);
ListNode head2 = mid.next;
mid.next = null;
//head排序后会发生改变,此处容易忘记 head= head2 =
head = mergeSort(head);
head2 = mergeSort(head2);
return merge(head,head2);
}
//合并
public static ListNode merge(ListNode head1,ListNode head2){
ListNode head = head1.val<head2.val?head1:head2;
if(head==head1){
head1 = head1.next;
}else {
head2 = head2.next;
}
ListNode cur = head;
while (head1!=null && head2!=null){
cur.next = head1.val<head2.val?head1:head2;
if(cur.next == head1){
head1 = head1.next;
}else {
head2 = head2.next;
}
cur = cur.next;
}
if(head1!=null){
cur.next = head1;
}
if(head2!= null){
cur.next = head2;
}
return head;
}
//获取中间节点
public static ListNode getMid(ListNode head){
ListNode slow = head;
ListNode fast = head;
//注意 fast.next.next
while (fast!=null && fast.next!=null && fast.next.next==null ){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
//错误的获取中间节点的方法
//1->2 此时mid.val=2, head2=mid.next=null,导致永远都是2+0的情况,不能归并
public static ListNode getMidWrong(ListNode head){
ListNode slow = head;
ListNode fast = head;
//注意 fast.next.next
while (fast!=null && fast.next!=null ){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
//另一种获取中间节点的方法
public static ListNode getMid2(ListNode head){
ListNode slow = head;
ListNode fast = head.next;
//注意 fast.next.next
while (fast!=null && fast.next!=null ){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
/**
* ---------------------------测试--------------------
* @param head
*/
public static void printList(ListNode head) {
if (head == null) {
System.out.println("null");
}
ListNode cur = head;
while (cur != null) {
System.out.printf(cur.val + " ");
cur = cur.next;
}
System.out.println();
}
public static void main(String[] args) {
ListNode listNode = new ListNode(2);
listNode.next = new ListNode(1);
listNode.next.next = new ListNode(3);
listNode.next.next.next = new ListNode(5);
listNode.next.next.next.next = new ListNode(4);
ListNode mid = getMid(listNode);
printList(listNode);
listNode = mergeSort(listNode);
printList(listNode);
}
}
coding-链表的插入、归并排序
最新推荐文章于 2021-07-05 16:00:47 发布