148. 排序链表 归并排序

148. 排序链表

难度:中等
题目描述
148. 排序链表 归并排序_第1张图片

解题思路

/*
		     * 148. 排序链表
		     * 2020/8/13
		     * 1对链表进行归并排序 
		     * 1、快慢指针找中间节点 
		     * 2、递归调用mergeSort 
		     * 3、合并有序链表
		     */
		    public ListNode sortList(ListNode head) {		    
		    	return listMergeSort(head);
		    }
		    public ListNode listMergeSort(ListNode head) {
		    	if(head == null || head.next == null)
		    		return head;
		    	ListNode fast = head,slow = head;
		    	while(fast != null && fast.next != null) {
		    		fast = fast.next.next;
		    		slow = slow.next;
		    	}
		    	// 对右半部分进行归并排序
		    	ListNode right = listMergeSort(slow.next);
		    	
		        // 链表判断结束的标志:末尾节点.next==null
		        slow.next = null;
		        // 对左半部分进行归并排序
		        ListNode left = listMergeSort(head);
		        return mergeList(left,right);
		    
		    }
			private ListNode mergeList(ListNode left, ListNode right) {
				ListNode nhead = new ListNode(-1);
				ListNode temp = nhead;
				while(left != null && right != null) {
					if(left.val < right.val) {
						nhead.next = left;
						left = left.next;
					}else {
						nhead.next = right;
						right = right.next;
					}
					nhead = nhead.next;
				}
				if(left != null)
					nhead.next = left;
				if(right != null)
					nhead.next = right;
				
				return temp.next;
			}

148. 排序链表 归并排序_第2张图片

你可能感兴趣的:(力扣刷题笔记)