## Main.java
public class Main {
public static void main(String[] args) {
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
n1.next = n2;
n2.next = n3;
Node c1 = new Node(1);
Node c2 = new Node(2);
Node c3 = new Node(3);
c1.next = c2;
c2.next = c3;
Node result = combine(n1, c1);
for (Node cur = result; cur != null; cur = cur.next) {
System.out.println(cur);
}
}
public static Node combine (Node head, Node head2){
Node cur1 = head;
Node cur2 = head2;
Node result = null;
Node last = null;//last记录最后一个节点
while (cur1 != null && cur2 != null) {
if (cur1.val < cur2.val) {
Node next = cur1.next;
if (result == null) {
result = cur1;
} else {
last.next = cur1;
}
last = cur1;
cur1 = next;
} else {
Node next = cur2.next;
if (result == null) {
result = cur2;
} else {
last.next = cur2;
}
last = cur2;
cur2 = next;
}
}
if (cur1 != null) {
last.next = cur1;
} else {
last.next = cur2;
}
return result;
}
}
## Node.java
public class Node{
public int val;
public Node next;
public Node(int val){
this.val=val;
}
public String toString(){
return String.format("Node(%d)",val);
}
}
【Java】链表的合并,合并后仍有序
最新推荐文章于 2024-01-13 11:45:48 发布