链表插入排序 lintcode

ゝ一纸荒年。 2022-07-16 12:09 330阅读 0赞

链表插入排序

难度系数 容易 通过率 31%

  • 描述
  • 笔记
  • 数据
  • 评测

用插入排序对链表排序

您在真实的面试中是否遇到过这个题?

Yes

样例

Given 1->3->2->0->null, return 0->1->2->3->null

``

  1. package tju.cs.bigdata.chc;
  2. public class ListNode {
  3. int val;
  4. ListNode next;
  5. ListNode(int val) {
  6. this.val = val;
  7. this.next = null;
  8. }
  9. public ListNode createList(String s){
  10. ListNode res = new ListNode(-1);
  11. String[] strings = s.split("->");
  12. ListNode cur = res;
  13. for(String st : strings){
  14. if(!st.equals("null"))cur.next = new ListNode(Integer.parseInt(st));
  15. cur = cur.next;
  16. }
  17. return res.next;
  18. }
  19. public void printList(ListNode l){
  20. ListNode cur = l;
  21. if(l == null)return;
  22. while(cur != null){
  23. System.out.print(cur.val + " ");
  24. cur = cur.next;
  25. }
  26. }
  27. }
  28. package tju.cs.bigdata.chc;
  29. public class InsertionSortList {
  30. public ListNode insertionSortList(ListNode head) {
  31. // write your code here
  32. if(head == null || head.next == null){
  33. return head;
  34. }
  35. ListNode res = new ListNode(-1);
  36. ListNode cur = head;
  37. ListNode curtmp = res;
  38. while(cur != null){
  39. curtmp = res;
  40. while(curtmp.next != null && curtmp.next.val <= cur.val){
  41. curtmp = curtmp.next;
  42. }
  43. // curtmp.printList(curtmp);
  44. // cur.printList(cur);
  45. ListNode l = cur.next;
  46. cur.next = curtmp.next;
  47. curtmp.next = cur;
  48. cur = l;
  49. // if(cur != null)cur.printList(cur);
  50. // curtmp.printList(curtmp);
  51. }
  52. return res.next;
  53. }
  54. public static void main(String[] args){
  55. String string = "1->3->2->0->null";
  56. ListNode res = new ListNode(-1).createList(string);
  57. res.printList(res);
  58. InsertionSortList insertionSortList = new InsertionSortList();
  59. ListNode res1 = insertionSortList.insertionSortList(res);
  60. res1.printList(res1);
  61. }
  62. }

发表评论

表情:
评论列表 (有 0 条评论,330人围观)

还没有评论,来说两句吧...

相关阅读

    相关 166-对进行插入排序

    题目如下: 对一条链表进行排序算法,要求使用算法为插入排序,且时间复杂度符合O(n^2) 解题方法: 1、判断链表是否为空,为空直接返回 2、新建排序链表头和尾都

    相关 插入排序算法

    如果数据存储在一段连续的内存上,比如数组中,插入排序算法的实现相信大家都已经非常熟悉,如果要对一个单链表进行插入排序,将会牵扯到大量指针操作。 同时,如果在实现的过

    相关 双向循环插入排序

    前两篇博文,我讨论了链表的冒泡排序和选择排序(以Linux内核链表为例),这篇文章,我想说说插入排序。 一、复习数组的插入排序 插入排序在算法思想中属于“减治法”。