题目链接

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

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

     public ListNode sortList(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode cur = null, tail = null;
cur = head;
while(cur.next != tail) {
while(cur.next != tail) {
//其实这里交换的是两个相邻结点的值,并没有交换两个结点指针
if(cur.val > cur.next.val) {
int tmp = cur.val;
cur.val = cur.next.val;
cur.next.val = tmp;
}
cur = cur.next;
}
//每一趟排序都会把一个相对最大的数排到最后一个,所以这里要将tail置为cur,而不是一直是null
tail = cur;//下一次遍历的尾结点是当前结点
//每一趟都再次从头开始遍历
cur = head;//遍历起始结点重置为头结点
}
return head;
}

法二:归并,交换结点,利用尾插,谁小谁放在前面。代码如下(耗时7ms):

     public ListNode sortList(ListNode head) {
if(head == null || head.next == null) {
return head;
}
//划分成两个链表,由快慢指针得到。
//最终slow会指向第二个链表的起始位置,fast会指向第二个链表的末尾,pre会指向第一个链表的末尾
ListNode pre = null, slow = head, fast = head;
while(fast != null && fast.next != null) {
pre = slow;
slow = slow.next;
fast = fast.next.next;
}
//第一个链表的终结
pre.next = null;
//分别对两个链表进行排序
//head是第一个链表的头,slow是第二个链表的头
ListNode l1 = sortList(head);
ListNode l2 = sortList(slow);
//归并l1和l2
return merge(l1, l2);
}
private static ListNode merge(ListNode l1, ListNode l2) {
//l头节点初始化为0,返回的时候返回l.next即可,即不带头结点的指针
ListNode l = new ListNode(0), p = l;
while(l1 != null && l2 != null) {
//尾插
if(l1.val < l2.val) {
p.next = l1;
l1 = l1.next;
}
else {
p.next = l2;
l2 = l2.next;
}
p = p.next;
}
//如果还有结点,则直接放在其后即可
if(l1 != null) {
p.next = l1;
}
if(l2 != null) {
p.next = l2;
}
return l.next;
}

最新文章

  1. 仿JQ基础架构,可扩展。
  2. Authcode()
  3. 移动APP项目研发流程及版本规划(转)
  4. JAVA实现复制文件夹
  5. eclipse配置javacv0.8
  6. HDU 4915 Parenthese sequence
  7. [转][C/C++]函数名字修饰(Decorated&#160;Name)方式
  8. c语言变量作用域问题
  9. servlet的生命周期与工作原理、使用!
  10. codeforce 605BE. Freelancer&#39;s Dreams
  11. Tasks on 2013
  12. JAVA锁的可重入性
  13. css position 应用(absolute和relative用法)
  14. [Leetcode][Python]40: Combination Sum II
  15. WebADI应用到Office 2016 64-bit
  16. deque (STL)
  17. java初级开发程序员(第二单元)
  18. Android开发技巧——定制仿微信图片裁剪控件
  19. MySQL 5.6.20-enterprise-commercial的参数文件位置问题
  20. textarea高度自适应自动展开

热门文章

  1. malloc与free函数用法
  2. C++11Mutex(互斥锁)详解
  3. WlanGetAvailableNetworkList
  4. 洛谷 P3241 [HNOI2015]开店 解题报告
  5. 使DIV相对窗口大小左右拖动始终水平居中
  6. python基础(5)
  7. skip-external-locking --mysql配置说明
  8. Idea安装findbugs插件,以及findbugs安装find security bugs插件
  9. 使用jconsole工具来监控java运行情况
  10. mysql 查询小demo