单链表排序

单链表的排序

方法1:利用归并排序(递归)

具体步骤:

  1. 使用快慢指针找到链表分割的中点
  2. 将链表分割成两个链表
  3. 对链表进行合并,合并成两个有序链表。
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) {
        // write code here
        //快慢指针找到链表的中点
        //分割链表
        //利用合并排序链表进行合并
        //1.首先判断链表是否为空,递归的终止条件
        if(head==null || head.next==null){
            return head;
        }
        //2.找到分割中点,将链表分为两个链表
        ListNode slow=head;
        ListNode fast=head.next.next;
        while(fast!=null && fast.next!=null){
            slow=slow.next;
            fast=fast.next.next;
        }
       
        ListNode rightNode=slow.next;//右边链表的开始
        slow.next=null;
        //递归继续分解链表
        ListNode left=sortInList(head);
        ListNode right=sortInList(rightNode);
        
        //递归的返回值为返回排序好的链表
        return merge(left,right);
    }
    //对两个链表进行排序合并
    public ListNode merge(ListNode list1,ListNode list2){
        //首先判断两个链表是否为空
        if(list1==null){return list2;}
        if(list2==null){return list1;}
        //然后两两比较链表中的元素
        ListNode result=new ListNode(0);
        ListNode cur=result;
        while(list1!=null && list2!=null){ 
            if(list1.val<=list2.val){
                cur.next=list1;
                list1=list1.next;
            }
            else{
                cur.next=list2;
                list2=list2.next;
            }
            cur=cur.next;
        }
        if(list1!=null){
            cur.next=list1;
        }
        if(list2!=null){
            cur.next=list2;
        }
        return result.next;
    }
}

方法2 利用数组进行排序

步骤为:

  1. 将链表中的元素加入数组
  2. 对数组进行排序
  3. 按照数组排序的数组加入到链表中
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) {
        // write code here
        //遍历链表,将节点加入数组
        //对数组进行排序
        //修改链表为排序后的链表
        ArrayList<Integer> nums=new ArrayList();
        ListNode p=head;
        //遍历链表
        while(p!=null){
            nums.add(p.val);
            p=p.next;
        }
        p=head;
        //排序
        Collections.sort(nums);
        //修改
        for(int i=0; i<nums.size();i++){
            p.val=nums.get(i);
            p=p.next;
        }
        return head;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值