leetCode解题报告之Insertion Sort List

曾经终败给现在 2022-08-25 15:44 278阅读 0赞

题目:

Sort a linked list using insertion sort.

分析:

这个题目是想要让我们来做一个链表的插入排序问题.

这样,我们只要从第一个元素一直往后,直到所有的节点都在前面的序列中找到自己所在的位置即可

情况:

  1. 当前值比head的值还小,这情况要插入到head节点之前

  2. 当前值比head的值大,这情况要插入到相应的位置

  3. 当前值大于所有该节点之前的值,那么当cmpNode(用来作比较的结点)和自身相等的时候,只要将当前结点(nowNode)往后挪一个结点进行下一个结点的比较即可.

解题思路:

大家都知道,如果要在一个位置插入一个结点,那么要知道它的前一个位置的结点才可以,所以为了满足“情况1”,我们引入一个结点preHead(head的前一个结点),它的next域指向head。

接着引入一个 nowNode(当前结点) 和 一个 preNowNode(当前结点的前驱结点)【处于nowNode之前的那些结点是已经排好序了】

最后在引入一个cmpNode(做比较的结点) 和一个preCmpNode(正在做比较的结点的前驱结点) 【从head 直到 nowNode ,依次取出来 和 nowNode做比较,确定nowNode要插入的位置】

有了上面的这些介绍,剩下的看代码,应该就容易多了!!

附个过程图解:

SouthEast

  1. package cn.xym.leetcode;
  2. class ListNode {
  3. public int val;
  4. public ListNode next;
  5. ListNode(int x) {
  6. val = x;
  7. next = null;
  8. }
  9. }
  10. public class Solution {
  11. public static void main(String[] args) {
  12. ListNode head = new ListNode(10);
  13. ListNode head1 = new ListNode(3);
  14. ListNode head2 = new ListNode(8);
  15. ListNode head3 = new ListNode(22);
  16. ListNode head4 = new ListNode(15);
  17. ListNode head5 = new ListNode(50);
  18. head.next = head1;
  19. head1.next = head2;
  20. head2.next = head3;
  21. head3.next = head4;
  22. head4.next = head5;
  23. head5.next = null;
  24. head = insertionSortList(head);
  25. while (head != null){
  26. System.out.println(head.val);
  27. head = head.next;
  28. }
  29. }
  30. public static ListNode insertionSortList(ListNode head) {
  31. if (head == null || head.next == null) {
  32. return head;
  33. }
  34. ListNode preHead = new ListNode(Integer.MIN_VALUE);
  35. preHead.next = head;
  36. ListNode nowNode = head.next, preNowNode = head;
  37. while (nowNode != null){
  38. ListNode cmpNode = head;
  39. ListNode precmpNode = preHead;
  40. while (cmpNode != null && !cmpNode.equals(nowNode)){
  41. if (cmpNode.val > nowNode.val){
  42. if (cmpNode.equals(head)){
  43. preNowNode.next = nowNode.next;
  44. nowNode.next = preHead.next;
  45. preHead.next = nowNode;
  46. head = nowNode;
  47. nowNode = preNowNode.next;
  48. }else{
  49. preNowNode.next = nowNode.next;
  50. nowNode.next = precmpNode.next;
  51. precmpNode.next = nowNode;
  52. nowNode = preNowNode.next;
  53. }
  54. break;
  55. }else{
  56. precmpNode = cmpNode;
  57. cmpNode = cmpNode.next;
  58. }
  59. }
  60. if (cmpNode.equals(nowNode)){
  61. preNowNode = nowNode;
  62. nowNode = preNowNode.next;
  63. }
  64. }
  65. return preHead.next;
  66. }
  67. }

发表评论

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

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

相关阅读