package com.basic.datastructure;
//合并两个有序链表,合并后依然有序
public class MergeList {
/**1.非递归
* (1)同时遍历两个链表的各自节点
* (2)进行值的比较,哪个值比较小,选哪个节点放入新链表中
* (3)添加至新链表的方式是尾插
* (4)当一个链表中的结点被全部取走后,直接将剩余的另一个链表接到结果链表后就可以了
*
* @param list1
* @param list2
* @return
*/
public static Node mergeListNode(Node list1,Node list2){
if(list1==null) return list2;
if(list2==null) return list1;
Node curA=list1;
Node curB=list2;
Node rst=null;//记录结果链表的第一个结点点
Node lastNode=null;//记录结果链表的最后一个结点
while(curA!=null && curB!=null){
if(curA.val <= curB.val){
if(rst==null){
rst=curA;
}else{
lastNode.next=curA;
}
lastNode=curA;
curA=curA.next;
}else {
if(rst==null){
rst=curB;
}else {
lastNode=curB;
}
lastNode=curB;
curB=curB.next;
}
}
if(curA!=null){
lastNode.next=curA;
}else {
lastNode.next=curB;
}
return rst;
}
//打印链表
public static void printListNode(Node head) {
Node cur = head;
while (cur.next!= null) {
System.out.print(cur.val + "->");
cur = cur.next;
}
System.out.print(cur.val);
}
public static void main(String[] args) {
Node node1=new Node(1);
Node node2=new Node(3);
Node node3=new Node(3);
Node node4=new Node(5);
Node node5=new Node(7);
node1.next=node2;
node2.next=node3;
node3.next=node4;
node4.next=node5;
printListNode(node1);
System.out.println();
Node node6=new Node(2);
Node node7=new Node(3);
Node node8=new Node(5);
Node node9=new Node(8);
node6.next=node7;
node7.next=node8;
node8.next=node9;
printListNode(node6);
System.out.println();
Node rstNode1=mergeListNode(node1,node6);
printListNode(rstNode1);
}
}
运行结果: