Insertion Sort List

来源:互联网 发布:mac qq截图不能用 编辑:程序博客网 时间:2024/05/20 23:37

Q:

Sort a linked list using insertion sort.

Solution:

/** * 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)            return head;        ListNode cur = head.next;        while (cur != null) {            ListNode temp = head;            while (temp.val <= cur.val && temp != cur)                temp = temp.next;            if (temp != cur) {                while (temp != cur) {                    int tempvalue = temp.val;                    temp.val = cur.val;                    cur.val = tempvalue;                    temp = temp.next;                }            }            cur = cur.next;        }        return head;    }}


0 0
原创粉丝点击