题目链接

题目大意:对链表进行排序,要求时间复杂度是o(nlgn)。

法一:冒泡,不交换结点,而交换结点中的数值。超时了。代码如下:

 1     public ListNode sortList(ListNode head) {
 2         if(head == null || head.next == null) {
 3             return head;
 4         }
 5         ListNode cur = null, tail = null;
 6         cur = head;
 7         while(cur.next != tail) {
 8             while(cur.next != tail) {
 9                 //其实这里交换的是两个相邻结点的值,并没有交换两个结点指针
10                 if(cur.val > cur.next.val) {
11                     int tmp = cur.val;
12                     cur.val = cur.next.val;
13                     cur.next.val = tmp;
14                 }
15                 cur = cur.next;
16             }
17             //每一趟排序都会把一个相对最大的数排到最后一个,所以这里要将tail置为cur,而不是一直是null
18             tail = cur;//下一次遍历的尾结点是当前结点
19             //每一趟都再次从头开始遍历
20             cur = head;//遍历起始结点重置为头结点
21         }
22         return head;
23     }
View Code

相关文章:

  • 2021-12-15
  • 2022-12-23
  • 2021-10-12
  • 2022-12-23
  • 2022-12-23
  • 2021-10-07
  • 2021-06-22
  • 2021-11-28
猜你喜欢
  • 2022-12-23
  • 2022-01-21
  • 2021-06-18
  • 2021-08-02
  • 2022-12-23
  • 2021-09-23
  • 2021-07-02
相关资源
相似解决方案