算法-链表-排序链表

在这里插入图片描述
在这里插入图片描述

方法一 递归

/**
 * 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;
        }
		//采用递归的方式  将head后面的节点排好序,然后将头节点插到适当的位置
        ListNode newHead = sortList(head.next);
        ListNode p = newHead;
        //这种情况直接往第一个插
        if(head.val <= p.val) {
    
    
            head.next = newHead;
            return head;
        }
		//找到要插入节点的前一个结点
        boolean flag = false;//标志位  true表示找到了 false表示没有找到
        while(p.next != null) {
    
    

            if(p.next.val > head.val) {
    
    
                flag = true;
                break;
            }

            p = p.next;

        }
		//找到了  开插
        if(flag) {
    
    
            head.next = p.next;
            p.next = head;
            //没找到直接查到最后
        }else {
    
    
            p.next = head;
            head.next = null;
        }

        return newHead;

    }
}

方法二 哈希表

/**
 * 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 insertionSortList(ListNode head) {
    
    
        List<Integer> list = new ArrayList<>();

        while(head != null) {
    
    
            list.add(head.val);
            head = head.next;
        }
        list.sort((o1, o2)->{
    
    
            return o1 - o2;
        });
        ListNode p = new ListNode(0);
        ListNode temp = p;
        for(int a : list) {
    
    
            temp.next = new ListNode(a);
            temp = temp.next;
        }

        return p.next;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45100361/article/details/113177740
今日推荐