147. Insertion Sort List

来源:互联网 发布:乐视系统优化怎么样 编辑:程序博客网 时间:2024/04/25 07:30

用插入排序对链表进行排序  


输出正确但是提交错误。。

以下思路 point.next指向每一个待比较的节点,将这个待比较的节点值与之前已排序的每一个节点值进行比较。找到对应的插入位置;


更快的思路,将point与point.next比较如果point.next.val<point.val 再将point.next找相应的位置进行插入 而不是每次都要进行比较

问题:对插入算法不熟悉。


public class Solution {    public ListNode insertionSortList(ListNode head) {        ListNode newhead1=new ListNode(0);        newhead1.next=head;        ListNode point=newhead1;        ListNode curn=new ListNode(0);        ListNode cur=new ListNode(0);               while(point.next!=null){   //因为涉及到下个节点的连接 所以使用next操作,避免使用本节点之后 无法找到上个节点进行删除                      int value=point.next.val;           cur=newhead1;           while(point.next!=cur.next&&point.next!=null){               if(value>=cur.next.val){                   cur=cur.next;               }               else{                   curn=cur.next;                   cur.next=point.next;                   point.next=point.next.next;                   cur.next.next=curn;                   break;               }           }           if(point.next!=null&&point.next.val==cur.next.val){               point=point.next;           }                  }     return newhead1.next;      }}


便捷解法

public class Solution {    public ListNode insertionSortList(ListNode head) {        if(head==null||head.next==null) return head;        ListNode newhead1=new ListNode(0);        newhead1.next=head;        ListNode point=head;        ListNode curn=new ListNode(0);        ListNode cur=new ListNode(0);               while(point.next!=null){                      if(point.val>point.next.val){             cur=newhead1;             while(cur.next.val<point.next.val)                cur=cur.next;             curn=point.next;             point.next=point.next.next;             curn.next=cur.next;             cur.next=curn;          }           else point=point.next;                 }     return newhead1.next;      }}


0 0