题目:
输入两个递增排序的链表,合并之后仍有序。
分析一:
使用递归。
代码一:
package offer.xzs.twentyone2thirty.twentyfive;
public class Demo01 {
public static void main(String[] args) {
ListNode head1 = new ListNode(1);
ListNode node1 = new ListNode(2);
ListNode node2 = new ListNode(5);
ListNode node3 = new ListNode(7);
ListNode node4 = new ListNode(9);
ListNode head2 = new ListNode(2);
ListNode node5 = new ListNode(4);
ListNode node6 = new ListNode(6);
ListNode node7 = new ListNode(8);
head1.setNext(node1);
node1.setNext(node2);
node2.setNext(node3);
node3.setNext(node4);
node4.setNext(null);
head2.setNext(node5);
node5.setNext(node6);
node6.setNext(node7);
node7.setNext(null);
ListNode head = getHead(head1, head2);
System.out.println(head);
}
public static ListNode getHead(ListNode head1, ListNode head2) {
if (head1 == null) {
return head2;
} else if (head2 == null) {
return head1;
}
if (head1.getValue() <= head2.getValue()) {
head1.setNext(getHead(head1.getNext(), head2));
return head1;
} else {
head2.setNext(getHead(head1, head2.getNext()));
return head2;
}
}
}
分析二:
新建一个头节点,进行重新连接。非递归。
代码二:
package offer.xzs.twentyone2thirty.twentyfive;
public class Demo02 {
public static void main(String[] args) {
ListNode head1 = new ListNode(1);
ListNode node1 = new ListNode(2);
ListNode node2 = new ListNode(5);
ListNode node3 = new ListNode(7);
ListNode node4 = new ListNode(9);
ListNode head2 = new ListNode(2);
ListNode node5 = new ListNode(4);
ListNode node6 = new ListNode(6);
ListNode node7 = new ListNode(8);
head1.setNext(node1);
node1.setNext(node2);
node2.setNext(node3);
node3.setNext(node4);
node4.setNext(null);
head2.setNext(node5);
node5.setNext(node6);
node6.setNext(node7);
node7.setNext(null);
ListNode head = getHead(head1, head2);
System.out.println(head);
}
public static ListNode getHead(ListNode head1, ListNode head2) {
ListNode newNode = new ListNode(-1);
ListNode cur = newNode;
while (head1 != null && head2 != null) {
if (head1.getValue() <= head2.getValue()) {
cur.setNext(head1);
head1 = head1.getNext();
} else {
cur.setNext(head2);
head2 = head2.getNext();
}
cur = cur.getNext();
}
if (head1 != null) {
cur.setNext(head1);
}
if (head2 != null) {
cur.setNext(head2);
}
return newNode.getNext();
}
}