Insertion Sort List, Leetcode 解题笔记

Sort a linked list using insertion sort.

回忆insertion sort的概念,很容易实现,对于list的操作关键还是要细心。

/**
 * 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) {
        ListNode newHead = new ListNode(Integer.MIN_VALUE);
        while(head != null){
            ListNode cur = newHead;
            while(cur.next != null && head.val > cur.next.val){
                cur = cur.next;
            }
            ListNode temp = cur.next;
            ListNode temp2 = head.next;
            cur.next = head;
            head.next = temp;
            head = temp2;
        }
        return newHead.next;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s