leetcode:Insertion Sort List

来源:互联网 发布:windows测试udp端口 编辑:程序博客网 时间:2024/06/05 20:03


单链表的插入排序


/** * 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) {                ListNode otherHead = null;                otherHead = head.next;                head.next = null;                while (otherHead != null) {                    ListNode node = otherHead;                    otherHead = otherHead.next;                    node.next = null;                    ListNode t = head;                    ListNode pre = head;                    while(t != null){                        if(t.val > node.val){                            break;                        }                        pre = t;                        t = t.next;                    }                    if(t == pre){                        node.next = t;                        head = node;                    }                    else{                        pre.next = node;                        node.next = t;                    }                }            }            return head;        }}


0 0
原创粉丝点击