前言
链表操作主要在于断链+合并。常用的重要思想是bottom-to-up + dummy。
一、案例
1)链表排序
2)链表合并
二、题解
1)链表排序
package com.xhu.offer.offerII;
public class SortList {
public ListNode sortList(ListNode head) {
ListNode p = head;
int len = 0;
while (p != null) {
len++;
p = p.next;
}
ListNode dummyHead = new ListNode(0, head);
ListNode pre = dummyHead;
for (int i = 1; i < len; i <<= 1) {
ListNode cur = head;
while (cur != null) {
ListNode l1 = cur;
int count = 1;
while (count++ < i && cur.next != null) cur = cur.next;
ListNode l2 = cur.next;
cur.next = null;
cur = l2;
count = 1;
while (count++ < i && cur != null) cur = cur.next;
ListNode next = null;
if (cur != null) {
next = cur.next;
cur.next = null;
}
l1 = merge(l1, l2);
pre.next = l1;
while (l1.next != null) l1 = l1.next;
pre = l1;
cur = next;
}
}
return dummyHead.next;
}
private ListNode merge(ListNode l1, ListNode l2) {
ListNode dummyNode = new ListNode(0);
ListNode cur = dummyNode;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
cur.next = l1;
l1 = l1.next;
} else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
cur.next = l1 != null ? l1 : l2;
return dummyNode.next;
}
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
}
2)链表合并
package com.xhu.offer.offerII;
public class MergeKLists {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
int len = lists.length;
for (int step = 1; step < len; step <<= 1) {
for (int i = 0; i < len - step; i += 2 * step) {
ListNode head = merge(lists[i], lists[i + step]);
lists[i] = head;
}
}
return lists[0];
}
private ListNode merge(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode();
ListNode cur = dummyHead;
for (; l1 != null && l2 != null; cur = cur.next) {
if (l1.val < l2.val) {
cur.next = l1;
l1 = l1.next;
continue;
}
cur.next = l2;
l2 = l2.next;
}
cur.next = l1 != null ? l1 : l2;
return dummyHead.next;
}
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
}
总结
1)题刷多了,知识点就没那么重要了,一定要把逻辑理顺,才能有好的理解以及优雅的代码。
参考文献
[1] 链表排序 [2] 多链表合并
|