首页 > 学院 > 开发设计 > 正文

leetcode经典编程题(5)

2019-11-06 09:33:02
字体:
来源:转载
供稿:网友

第(5)题 insertion-sort-list 知识点:排序 题述:Sort a linked list using insertion sort. 用插入排序对一个链表进行排序。 思路:插入排序就是将一组数分为两组,前一组是已经排好序的,后一组是为排序的。 具体实现要两重遍历,第一重是对未排序的进行遍历,第二重是对已经排好序的进行遍历,选择合适的位置插入元素。 代码如下:

/** * 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 temp = new ListNode(Integer.MIN_VALUE); ListNode cur = head; ListNode PRe = temp; while( cur != null ){ ListNode next = cur.next; pre = temp; while( pre.next != null && pre.next.val < cur.val){ pre = pre.next; } cur.next = pre.next; pre.next = cur; cur = next; } return temp.next; }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表