题解 | #链表排序#

链表排序

http://www.nowcoder.com/practice/d75c232a0405427098a8d1627930bea6

//归并排序
注意合并时 排序使用两个指针 ,避免两次循环的排序方法

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
      public ListNode sortList (ListNode head) {
         if(head==null||head.next==null){
            return head;
        }
        //分
        ListNode mid = getmid(head);
        ListNode head2 = mid.next;
        mid.next=null;

        head=sortList(head);
        head2=sortList(head2);
        //归
        head = merge(head,head2);
        return head;
    }

    public ListNode merge(ListNode head1,ListNode head2){
        //定义两个指针结点
        ListNode temp2 = head2;
        ListNode head = new ListNode(0);//任意设置一个临时首节点
        head.next=head1;//定义一个临时首结点
        ListNode temp1 = head;

        while(temp1.next!=null&&temp2!=null){//边界条件
            //指针移动比较两指针结点处的val值

            //如果temp1.next<temp2的val值,将temp2的val赋给node,并插入head1中, 使用temp1.next的原因是便于
            //找到比较结点的上一个节点,方便插入
            if(temp1.next.val>temp2.val){
                //temp2结点复制到node,temp2指针向后移动一位,node断链
                ListNode node = temp2;
                temp2=temp2.next;
                node.next=null;

                //将node插入到head1中,更新temp1
                node.next=temp1.next;
                temp1.next=node;
                temp1=node;
            }else{//如果>=则,temp1向后移动

                temp1=temp1.next;
            }
        }
        //若temp1.next==null,则将temp2的后续元素全部插入到temp1之后
        if(temp1.next==null){
            temp1.next=temp2;
        }
        return head.next;
    }



    public ListNode getmid(ListNode head){
        ListNode temp = head;
        int count = 1;
        while(temp.next!=null){
            temp=temp.next;
            count++;
        }
        if(count==2){
            return head;
        }
        int mid = count/2+1;
        temp = head;

        while(count!=mid){
            temp=temp.next;
            count--;
        }
        return temp;  
    }
}
全部评论

相关推荐

HR_丸山彩同学:你的项目描述里,系统设计讲了很多:MemCube是什么、三级存储架构怎么设计、四种遗忘策略分别是什么。这些面试的时候讲没问题,但简历上不需要这么细。 简历要突出的是影响力,不是实现细节。面试官看简历的时候想知道的是「这个项目有多大价值」,不是「这个项目具体怎么实现的」。实现细节是面试时候聊的 怎么改:技术细节可以精简为一句「采用三级存储架构+四种遗忘策略」,把省出来的篇幅用来写影响力。比如:项目有没有开源?有没有写成技术博客?有没有被别人使用过? 校园经历没有任何信息量,任何人都可以写这句话,写了等于没写。更关键的是,你投的是技术岗,校园活动经历本来就不是加分项。如果非要写,必须写出具体的数字和成果。如果你没有这些数字,那就老老实实删掉 「端到端耗时缩减30-40%」要给出确切数字和绝对值。从1000ms降到600ms是降了40%,从100ms降到60ms也是降了40%,但这两个含义完全不一样。其他也是,涉及到数据,准备好证据,口径统一,面试会问 「熟练」「熟悉」「了解」混在一起用,读起来很乱。而且「了解前端需求」最好改成「具备前后端协作经验」
点赞 评论 收藏
分享
评论
点赞
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务