2022-4-4 高频面试题

给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode() {}
 7  *     ListNode(int val) { this.val = val; }
 8  *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 9  * }
10  */
11 class Solution {
12     public ListNode sortList(ListNode head) {
13         ListNode dummy=new ListNode(-100001);
14         while (head!=null) {
15             insert(dummy,new ListNode(head.val));
16             head=head.next;
17         }
18         return dummy.next;
19     }
20 
21     public void insert(ListNode dummy,ListNode node){
22         ListNode head=dummy,pre=dummy;
23         while (head!=null&&node.val>head.val) {
24             pre=head;
25             head=head.next;
26         }
27         if (head==null) {
28             pre.next=node;
29         }else {
30             pre.next=node;
31             node.next=head;
32         }
33         return;
34     }
35 }

思路:插入排序。 可以归并排序。快慢指针确定中点,再各自排序合并。

posted on 2022-04-04 15:54  阿ming  阅读(17)  评论(0编辑  收藏  举报

导航