首页 > 试题广场 >

链表合并

[编程题]链表合并
  • 热度指数:3545 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
请编写一段代码,实现两个单向有序链表的合并

输入描述:
第一行一个链表,如1 2 3 4 5

第二行一个链表,如2 3 4 5 6


输出描述:
输出:1 2 2 3 3 4 4 5 5 6
示例1

输入

1 2 3 4 5
2 3 4 5 6

输出

1 2 2 3 3 4 4 5 5 6

import java.util.*;
//链表节点定义
class ListNode{
    int val;
    ListNode next;
    ListNode(int val){this.val = val;}
}

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        ListNode p1 = creatList(sc.nextLine().split(" "));
        ListNode p2 = creatList(sc.nextLine().split(" "));
        ListNode ansHead = mergeTwoLists(p1, p2);
        while(ansHead != null) {
            System.out.print(ansHead.val+" ");
            ansHead = ansHead.next;
        }
    }
    
    //创建链表函数
    public static ListNode creatList(String[] s){
        if(s == null || s.length == 0)
            return null;
        ListNode dummy = new ListNode(0);
        ListNode curNode = dummy;
        for(int i=0; i<s.length; i++) {
            curNode.next = new ListNode(Integer.parseInt(s[i]));
            curNode = curNode.next;
        }
        curNode.next = null;
        return dummy.next;
    }
    //合并链表函数
    public static ListNode mergeTwoLists(ListNode p1, ListNode p2){
        if(p1 == null)
            return p2;
        if(p2 == null)
            return p1;
        if(p1.val < p2.val){
            p1.next = mergeTwoLists(p1.next, p2);
            return p1;
        }else {
            p2.next = mergeTwoLists(p1, p2.next);
            return p2;
        }
    }
}

发表于 2020-07-27 18:39:09 回复(0)
//就本题而言讨巧的写法,转化为整数数组排序输出
import java.io.*;
import java.util.*;
public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] str1 = br.readLine().split(" ");
        String[] str2 = br.readLine().split(" ");
        int[] arr = new int[str1.length+str2.length];
        for(int i = 0;i < str1.length;i++){
            arr[i] = Integer.parseInt(str1[i]);
        }
        for(int j = 0;j < str2.length;j++){
            arr[str1.length+j] = Integer.parseInt(str2[j]);
        }
        Arrays.sort(arr);
        for(int i = 0;i < arr.length;i++){
            System.out.print(arr[i] + " ");
        }
    }
}

发表于 2020-04-09 19:24:29 回复(0)