首页 > 其他 > 详细

Insertion Sort List —— LeetCode

时间:2015-05-24 20:22:35      阅读:200      评论:0      收藏:0      [点我收藏+]

Sort a linked list using insertion sort.

题目大意:将一个单链表使用插入排序的方式排序。

解题思路:先新建一个头指针,然后重新构建一下这个单链表,每次从头找到第一个比当前元素大的,插在这个元素前面。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode insertionSortList(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }
        ListNode headPtr = new ListNode(0);
        while(head!=null){
            ListNode node = headPtr;
            ListNode tmp = head.next;
            while(node.next!=null&&head.val>node.next.val){
                node=node.next;
            }
            head.next=node.next;
            node.next=head;
            head=tmp;
        }
        return headPtr.next;
    }
}

 

Insertion Sort List —— LeetCode

原文:http://www.cnblogs.com/aboutblank/p/4526309.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!