题解 | #单链表的排序#

单链表的排序

https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    public ListNode sortInList (ListNode head) {
        // write code here
        if(head == null) {
            return null;
        }

        List<Integer> list = new ArrayList<>();

        
        ListNode loop = head;
        while(loop != null) {
            list.add(loop.val);
            loop = loop.next;
        }
                
        ListNode loop2 = head;

        // list.sort(Comparator.comparingInt(v -> v));
        // for(int i=0; i<list.size(); i++) {
        //     loop2.val = list.get(i);
        //     loop2 = loop2.next;
        // }
        Integer[] arr = list.toArray(new Integer[0]);
        sort(arr, 0, arr.length-1);
        for(int i=0; i<arr.length; i++) {
            loop2.val = arr[i];
            loop2 = loop2.next;
        }
        return head;
    }


    public void sort(Integer[] arr, int left, int right) {
        int keepLeft = left;
        int keepRight = right;

        if(left >= right) {
            return;
        }
        Integer base = arr[left];
        Integer slot = left;
        while(left < right) {
            while(left < right) {
                if(arr[right] < base) {
                    arr[slot] = arr[right];
                    slot = right;
                    break;
                }
                right--;
            }
            while(left < right) {
                if(arr[left] > base) {
                    arr[slot] = arr[left];
                    slot = left;
                    break;
                }
                left++;
            }
        }
        arr[slot] = base;
        sort(arr, keepLeft, slot-1);
        sort(arr, slot+1, keepRight);

    }


}

全部评论

相关推荐

双非本科小鼠:27兄弟,不应该还在享受校园吗哈哈😂
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务