问题:将两个升序的链表合并成一个新的升序链表
方法一:
思路分析:
创建一个新的链表pNode,而current一直指向插入的节点,循环比较链表A和链表B每个节点的值,满足条件就插入,同时去除该节点,current移动
代码实现:
public static Node mergeLinkedMethod1(Node nodeA,Node nodeB){
if(nodeA == null)return nodeB;
if(nodeB == null)return nodeA;
Node pNode = new Node(-1);
Node current = pNode;
while (nodeA != null && nodeB != null){//都不是空
if(nodeA.val < nodeB.val){
current.next = nodeA;
nodeA = nodeA.next;
}else {
current.next = nodeB;
nodeB = nodeB.next;
}
current = current.next;
}
//其中有一方循环遍历结束了,一方为空,但另一方可能还没有遍历结束
while(nodeA != null){
current.next = nodeA;
nodeA = nodeA.next;
current = current.next;
}
while(nodeB != null){
current.next = nodeB;
nodeB = nodeB.next;
current = current.next;
}
return pNode.next;
}
方法二:优化方法一
思路分析:
方法一中,当其中有一个链表结束了,此时链表为null,但另一方并没有结束,不再循环插入节点,直接把没结束的链表拼接到新链表中
代码实现:
public static Node mergeLinkedMethod2(Node nodeA,Node nodeB){
if(nodeA == null)return nodeB;
if(nodeB == null)return nodeA;
Node pNode = new Node(-1);
Node current = pNode;
while (nodeA != null && nodeB != null){//都不是空
if(nodeA.val < nodeB.val){
current.next = nodeA;
nodeA = nodeA.next;
}else {
current.next = nodeB;
nodeB = nodeB.next;
}
current = current.next;
}
//其中有一方循环遍历结束了,一方为空,但另一方可能还没有遍历结束
current.next = nodeA == null ? nodeB : nodeA;
return pNode.next;
}
问题:合并多个有序链表
思路分析:
其实类似于两个链表的拼接,循环两个链表的拼接即可
代码实现:
public static void main(String[] args) {
Integer[] arrA = new Integer[]{4,5,8,12};
Integer[] arrB = new Integer[]{6,8,15,17,19,25};
Node nodeA = ListNodeUtils.creatListNode(arrA);
Node nodeB = ListNodeUtils.creatListNode(arrB);
//合并k个链表
Integer[] arrC = new Integer[]{12,18,19,22};
Node nodeC = ListNodeUtils.creatListNode(arrC);
Node[] nodes = new Node[]{nodeA,nodeB,nodeC};
Node res = new Node(-1);
for (Node node : nodes) {
res = mergeLinkedMethod2(res, node);
}
res = res.next;
System.out.println(ListNodeUtils.toString(res));
}