题解 | #单链表的排序#
单链表的排序
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) {
// 思路1:构建辅助数组
if(head==null) {
return head;
}
List<Integer> temp = new ArrayList<>();
while(head!=null) {
temp.add(head.val);
head = head.next;
}
Collections.sort(temp);
ListNode result = new ListNode(-1);
ListNode tempList = result;
for(int i=0;i<temp.size();i++) {
ListNode tempNode = new ListNode(temp.get(i));
tempList.next = tempNode;
tempList = tempList.next;
}
return result.next;
}
}
辅助数组法:本题的关键在于理解链表的结构,注意 tempList.next = tempNode; tempList = tempList.next;
OPPO公司福利 1195人发布