单链表排序
(牛客网—牛客题霸算法篇—NC70)
题目描述
给定一个节点数为n的无序单链表,对其按升序排序。
思路
Java实现
可以将单链表的每一个节点看作是数组的索引下标,对单链表的排序就可以看作是对数组进行排序,但需要注意的是,单链表的排序只能用简单选择排序。
在使用简单选择排序时,只需要交换两个节点的值,而不需要交换节点,就像数组排序时,我们也只是交换对应位置的值,而没有把数组的索引下标进行交换(数组的索引下标是不能交换的哦,这里只是打个比方)
代码实现
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) {
ListNode first=head;
ListNode lnext=null;
int temp=0;
while(first!=null){
lnext=first.next;
while(lnext!=null){
if(lnext.val<first.val){
temp=first.val;
first.val=lnext.val;
lnext.val=temp;
}
lnext=lnext.next;
}
first=first.next;
}
return head;
}
}