Java单链表排序
作者:互联网
题目描述
给定一个无序单链表,实现单链表的排序(按升序排序)。
示例1
输入
[1,3,2,4,5]
返回值
{1,2,3,4,5}
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
public ListNode sortInList (ListNode head) {
if(head == null || head.next == null){
return head;
}
int len = 0;
ListNode tempNode = head;
while(tempNode!=null){
len++;
tempNode = tempNode.next;
}
int[] arr = new int[len];
ListNode tempNode2 = head;
for(int i=0;i<len;i++){
arr[i] = tempNode2.val;
tempNode2 = tempNode2.next;
}
Arrays.sort(arr);
int j = 0;
ListNode tempNode3 = head;
while(tempNode3!=null){
tempNode3.val = arr[j++];
tempNode3 = tempNode3.next;
}
return head;
}
}
标签:head,单链,ListNode,int,null,tempNode,next,Java,排序 来源: https://blog.csdn.net/luzhensmart/article/details/113844993