首页 > 代码库 > 【LeetCode】Insertion Sort List
【LeetCode】Insertion Sort List
Sort a linked list using insertion sort.
//用到O(N)的额外空间 public class Solution { public ListNode insertionSortList(ListNode head) { if(head==null||head.next==null) return head; ListNode root = new ListNode(head.val); ListNode cur = head.next; while(cur!=null){ ListNode tempNode = root; ListNode pre = root; while(tempNode!=null){ if(cur.val>tempNode.val){ pre=tempNode; tempNode=tempNode.next; }else{ break; } } if(tempNode==root){ ListNode newNode = new ListNode(cur.val); newNode.next=root; root=newNode; cur=cur.next; }else if(tempNode==null){ ListNode newNode = new ListNode(cur.val); pre.next=newNode; cur=cur.next; }else{ ListNode newNode = new ListNode(cur.val); pre.next=newNode; newNode.next=tempNode; cur=cur.next; } } return root; } }
public class NSolution { public ListNode insertionSortList(ListNode head) { if(head==null||head.next==null) return head; ListNode cur = head.next; head.next=null; while(cur!=null){ ListNode tempNode = head; ListNode pre = head; while(tempNode!=null){ if(cur.val>tempNode.val){ pre=tempNode; tempNode=tempNode.next; }else{ break; } } if(tempNode==head){ ListNode newNode = new ListNode(cur.val); newNode.next=head; head=newNode; cur=cur.next; }else if(tempNode==null){ ListNode newNode = new ListNode(cur.val); pre.next=newNode; cur=cur.next; }else{ ListNode newNode = new ListNode(cur.val); pre.next=newNode; newNode.next=tempNode; cur=cur.next; } } return head; } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。