程序员代码面试指南第二版 30.合并两个有序的单链表
题目描述
给定两个升序的单链表的头节点 head1 和 head2,请合并两个升序链表, 合并后的链表依然升序,并返回合并后链表的头节点。
输入描述:
两个升序的单链表的头节点 head1 和 head2
输出描述:
在给定的函数内返回新链表的头指针。
示例1
输入
5
1 2 3 4 5
6
7 8 9 10 11 12
输出
1 2 3 4 5 7 8 9 10 11 12
第一次做; 基础操作
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n1 = Integer.parseInt(sc.nextLine());
String[] str1 = sc.nextLine().split(" ");
int n2 = Integer.parseInt(sc.nextLine().trim());
String[] str2 = sc.nextLine().split(" ");
Node head1 = new Node(Integer.parseInt(str1[0]));
Node curr = head1;
for(int i=1; i<n1; i++){
curr.next = new Node(Integer.parseInt(str1[i]));
curr = curr.next;
}
Node head2 = new Node(Integer.parseInt(str2[0]));
curr = head2;
for(int i=1; i<n2; i++){
curr.next = new Node(Integer.parseInt(str2[i]));
curr = curr.next;
}
Node tmp = new Node(0);
curr = tmp;
Node curr1 = head1;
Node curr2 = head2;
while(curr1!=null && curr2!=null){
if(curr1.val <= curr2.val){
curr.next = curr1;
curr1 = curr1.next;
}
else{
curr.next = curr2;
curr1 = curr1.next;
}
curr = curr.next;
}
if(curr1==null)
curr.next = curr2;
if(curr2==null)
curr.next = curr1;
curr = tmp.next;
while(curr!=null){
System.out.print(curr.val+" ");
curr = curr.next;
}
}
public static class Node{
int val;
Node next;
Node(int val){
this.val = val;
}
}
}
可以通过的答案; 使用了StreamTokenizer
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
public class Main {
private static StreamTokenizer in =
new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
public static ListNode merge(ListNode list1, ListNode list2) {
ListNode head = new ListNode(0);
ListNode current = head;
ListNode p1 = list1;
ListNode p2 = list2;
while (p1 != null && p2 != null) {
if (p1.val < p2.val) {
current.next = p1;
current = p1;
p1 = p1.next;
} else {
current.next = p2;
current = p2;
p2 = p2.next;
}
}
current.next = p1 == null ? p2 : p1;
return head.next;
}
private static ListNode read() {
int size = nextInt();
ListNode head = new ListNode(0);
ListNode last = head;
for (int i = 0; i < size; i++) {
ListNode next = new ListNode(nextInt());
last.next = next;
last = next;
}
return head.next;
}
public static class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
private static int nextInt() {
try {
in.nextToken();
return (int) in.nval;
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
public static void main(String[] args) {
ListNode head1 = read();
ListNode head2 = read();
ListNode head = merge(head1, head2);
StringBuilder sb = new StringBuilder();
while (head != null) {
sb.append(head.val).append(" ");
head = head.next;
}
System.out.println(sb.toString());
}
}