题目:链表插入排序

用插入排序对链表排序

您在真实的面试中是否遇到过这个题?
Yes
哪家公司问你的这个题? Airbnb Alibaba Amazon Apple Baidu Bloomberg Cisco Dropbox Ebay Facebook Google Hulu Intel Linkedin Microsoft NetEase Nvidia Oracle Pinterest Snapchat Tencent Twitter Uber Xiaomi Yahoo Yelp Zenefits
感谢您的反馈
样例

Given 1->3->2->0->null, return 0->1->2->3->null

标签 Expand
排序 链表



相关题目 Expand




方法1:将所有的链表的val排序,然后重新新建链表
/**
* Definition for ListNode.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int val) {
*         this.val = val;
*         this.next = null;
*     }
* }
*/
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @return: The head of linked list.
     */
    public ListNode insertionSortList(ListNode head) {
        // write your code here
        if(head==null||head.next==null) return head;
         ListNode cur = head;
         ArrayList iList = new ArrayList<>();
         while(cur!=null){
              iList.add(cur.val);
              cur = cur.next;
         }
         Collections.sort(iList);
         ListNode xhead = new ListNode(iList.get(0));
         ListNode x = xhead;
         for(int i=1;i               x.next = new ListNode(iList.get(i));
              x = x.next;
         }
        
        return xhead;
    }
}
方法2:每次循环找到一个元素在当前排好的结果中相对应的位置,然后插进去,经过n次迭代之后就得到排好序的结果了。O(n^2)的时间复杂度

/**
* Definition for ListNode.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int val) {
*         this.val = val;
*         this.next = null;
*     }
* }
*/
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @return: The head of linked list.
     */
    public ListNode insertionSortList(ListNode head) {
        // write your code here
        if(head==null||head.next==null) return head;
        ListNode newx = new ListNode(0);
        ListNode cur = head;
        ListNode newcur = newx;
        while(cur!=null){
             ListNode curnext  = cur.next;
             newcur  = newx;
             while(newcur.next!=null&&newcur.next.val                   newcur = newcur.next;
             }
             cur.next = newcur.next;
             newcur.next = cur;
             cur = curnext;            
        }
        return newx.next;
    }
}





你可能感兴趣的:(题目:链表插入排序)