ACM模式输入输出链表
以合并两个有序链表为例:
- 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
https://leetcode.cn/problems/merge-two-sorted-lists/
输入:
1 2 4
1 3 4
输出结果为:
[1,1,2,3,4,4]
下面是非递归的写法:
import java.util.Scanner;
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public class demo001 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] params = scanner.nextLine().split(" ");
// int[] nums = new int[params.length];
ListNode dummy1 = new ListNode(-1);
ListNode dummy2 = new ListNode(-1);
ListNode cur1 = dummy1;
ListNode cur2 = dummy2;
for (String x : params) {
cur1.next = new ListNode(Integer.parseInt(x));
cur1 = cur1.next;
}
String[] params2 = scanner.nextLine().split(" ");
for (String x : params2) {
cur2.next = new ListNode(Integer.parseInt(x));
cur2 = cur2.next;
}
ListNode res = Merge(dummy1.next, dummy2.next);
System.out.print("[");
while (res != null) {
System.out.print(res.val);
if (res.next != null) {
System.out.print(",");
}
res = res.next;
}
System.out.print("]");
}
public static ListNode Merge(ListNode list1,ListNode list2){
ListNode node = new ListNode(-1);
ListNode pre = node;
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
pre.next = list1;
list1 = list1.next;
} else {
pre.next = list2;
list2 = list2.next;
}
pre = pre.next;
}
if (list1 != null) {
pre.next = list1;
}
if (list2 != null) {
pre.next = list2;
}
return node.next;
}
}
今日推歌
----《忽而今夏》 汪苏泷
可是你还记得吗
那年盛夏
那个傻瓜
说的傻话
陪着你回家
陪着你长大
每天都记得打电话