题目:
输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是递增排序的。
分析:
定义两个指针,分别指向这两个链表的第一个结点。当第一个结点的值小于第二个结点的值时,链表1的头结点将是合并后的链表的头结点。继续比较两个头结点,如果第二个结点的值小,链表2的头结点将是合并剩余结点得到的链表的头结点。
解法:
package com.wsy;
class Node {
private int value;
private Node next;
public Node() {
}
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
public class Main {
public static void main(String[] args) {
Node head1 = init1();
Node head2 = init2();
print(merge(head1, head2));
}
public static Node init1() {
Node node9 = new Node(9, null);
Node node7 = new Node(7, node9);
Node node5 = new Node(5, node7);
Node node3 = new Node(3, node5);
Node node1 = new Node(1, node3);
return node1;
}
public static Node init2() {
Node node10 = new Node(10, null);
Node node8 = new Node(8, node10);
Node node6 = new Node(6, node8);
Node node4 = new Node(4, node6);
Node node2 = new Node(2, node4);
return node2;
}
public static void print(Node node) {
while (node != null) {
System.out.print(node.getValue() + "->");
node = node.getNext();
}
System.out.println();
}
public static Node merge(Node head1, Node head2) {
if (head1 == null && head2 == null) {
return null;
}
Node head = null;
Node current = null;
while (head1 != null && head2 != null) {
if (head1.getValue() <= head2.getValue()) {
if (head == null) {
head = current = head1;
} else {
current.setNext(head1);
current = current.getNext();
}
head1 = head1.getNext();
} else {
if (head == null) {
head = current = head2;
} else {
current.setNext(head2);
current = current.getNext();
}
head2 = head2.getNext();
}
}
if (head1 == null) {
current.setNext(head2);
} else {
current.setNext(head1);
}
return head;
}
}