//两个有序链表合并
class Node{
Node next;
int data;
public Node(int data){
this.data = data;
}
}
public class Test6{
public static void main(String [] args){
Node L1 = new Node(1);
Node node1 = new Node(2);
Node node2 = new Node(3);
Node node3 = new Node(4);
L1.next = node1;
node1.next = node2;
node2.next = node3;
node3.next = null;
Node L2 = new Node(2);
Node node21 = new Node(3);
Node node22 = new Node(5);
Node node23 = new Node(9);
Node node24 = new Node(10);
L2.next = node21;
node21.next = node22;
node22.next = node23;
node23.next = node24;
node24.next = null;
Node newHead = merge(L1,L2);
while(newHead!= null){
System.out.printf("%s ",newHead.data);
newHead = newHead.next;
}
}
public static Node merge(Node L1, Node L2){
if(L1 == null){
return L2;
}
if(L2 == null){
return L1;
}
Node newHead = null; //新链表的头
Node cur = new Node(-1);
while(L1 != null && L2 != null){
//取当前节点最小值加入新链表
if(L1.data <= L2.data){
cur.next = L1;
cur = cur.next;
L1 = L1.next;
if(newHead == null){
newHead = cur;
}
}else{
cur.next = L2;
cur = cur.next;
L2 = L2.next;
if(newHead == null){
newHead = cur;
}
}
}
//判断哪个链表结尾还有节点没有遍历完
if(L1 != null){
cur.next = L1;
L1 = L1.next;
cur = cur.next;
}
if(L2 != null){
cur.next = L2;
L2 = L2.next;
cur = cur.next;
}
return newHead;
}
}
编程题-两个有序单链表合并
最新推荐文章于 2023-11-11 17:40:48 发布