首页 > 代码库 > [Leetcode] Insertion Sort List
[Leetcode] Insertion Sort List
Sort a linked list using insertion sort.
Solution:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * }10 * }11 */12 public class Solution {13 public ListNode insertionSortList(ListNode head) {14 if(head==null||head.next==null)15 return head;16 ListNode dummy=new ListNode(-1);17 ListNode pre,next;18 while(head!=null){19 pre=findPosition(dummy,head.val);20 next=pre.next;21 pre.next=new ListNode(head.val);22 pre.next.next=next;23 head=head.next;24 }25 return dummy.next;26 }27 28 private ListNode findPosition(ListNode dummy, int val) {29 // TODO Auto-generated method stub30 ListNode pre=dummy, next=pre.next;31 while(next!=null&&next.val<=val){32 next=next.next;33 pre=pre.next;34 }35 return pre;36 }37 }
[Leetcode] Insertion Sort List
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。