Leetcode-Insertion Sort List

来源:互联网 发布:快手制作视频软件 编辑:程序博客网 时间:2024/06/05 15:45

Sort a linked list using insertion sort.

AC代码:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode insertionSortList(ListNode head) {if( head == null || head.next == null){return head;}//1 create a new list with head is dummyHeadListNode dummyHead = new ListNode(-1);ListNode curr = head;ListNode dummyCurr = dummyHead;//2 insert first Node into dummyHeaddummyHead.next = curr;curr = curr.next;dummyHead.next.next = null;//3 insert list into dummyHeadwhile( curr != null){dummyCurr = dummyHead;while( dummyCurr.next.val <= curr.val ){//find the insert positionif( dummyCurr.next.next == null ){break;}else{dummyCurr = dummyCurr.next;}}//do insert the Nodeif ( dummyCurr.next.next == null && dummyCurr.next.val <= curr.val){dummyCurr.next.next = curr;curr = curr.next;//must do this heredummyCurr = dummyCurr.next;dummyCurr.next.next = null;}else{ListNode temp = curr;curr = curr.next;//must do this heretemp.next = dummyCurr.next;dummyCurr.next = temp;}}return dummyHead.next;    }}


0 0
原创粉丝点击