一 有序合并问题
两个有序链表,合并后仍然有序。
分析: 容易想到的就是找头,也就是判断下两个链表头结点val小的。然后采用尾部插入(从head插就覆盖了),遍历两个链表,每次取小的,知道有个链表为空退出。在判断有无剩余非空的链表,追加到尾部。
/**
*
* @author bohu83
*
*/
public class MergerList {
public static void main(String[] args) {
Node node1 = new Node(1);
node1.next = new Node(3);
node1.next.next = new Node(5);
node1.next.next.next = new Node(7);
node1.next.next.next = new Node(9);
Node node6 = new Node(2);
node6.next = new Node(4);
node6.next.next = new Node(5);
node6.next.next.next = new Node(8);
Node rstNode1 = mergeListNode(node1, node6);
while (rstNode1 != null) {
System.out.print("->" + rstNode1.val);
rstNode1 = rstNode1.next;
}
}
// list合并
public static Node mergeListNode(Node list1, Node list2) {
// conner case
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
Node res = null;
Node lastNode = null;// 记录结果链表的最后一个结点
Node curA = list1;
Node curB = list2;
while (curA != null && curB != null) {
// find head
if (curA.val <= curB.val) {
if (res == null) {
res = curA;
} else {
lastNode.next = curA;
}
lastNode = curA;
curA = curA.next;
} else {
if (res == null) {
res = curB;
} else {
lastNode.next = curB;
}
lastNode = curB;
curB = curB.next;
}
}
// 剩余插入尾
if (curA != null) {
lastNode.next = curA;
} else {
lastNode.next = curB;
}
return res;
}
static class Node {
int val;
Node next;
Node(int x) {
val = x;
}
}
}
->1->2->3->4->5->5->8->9