题解 | #链表合并#

链表合并

https://www.nowcoder.com/practice/27c833289e5f4f5e9ba3718ce9136759

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String first = scanner.nextLine();
            String second = scanner.nextLine();

            Node node1 = transform(first);
            Node node2 = transform(second);
            Node node = merge(node1, node2);


            print(node);
        }
    }


    public static Node merge(Node node1, Node node2) {
        // 找到最小的那个
        Node node = node1.value >= node2.value ? node2 : node1;
        Node cur1 = node.next;
        Node cur2 = node == node1 ? node2 : node1;
        Node pre = node;
        while (cur1 != null && cur2 != null) {
            pre.next = cur1.value >= cur2.value ? cur2 : cur1;
            pre = pre.next;
            // 下移动
            if (cur1 == pre) {
                cur1 = cur1.next;
            } else {
                cur2 = cur2.next;
            }
        }
// 如果其中一个是null后
        pre.next = cur1 == null ? cur2 : cur1;
        return node;
    }

    public static Node transform(String str) {
        Node node = null;
        Node pre = null;
        String array[] = str.split(" ");
        for (String s : array) {
            if (node == null) {
                node = new Node(Integer.parseInt(s));
                pre = node;
            } else {
                node.next = new Node(Integer.parseInt(s));
                node = node.next;
            }
        }
        return pre;
    }

    public  static void print(Node node) {
        while (node != null) {
            System.out.print(node.value + " ");
            node = node.next;
        }
    }
}

class Node {
    int value;
    Node next;
    public Node(int value) {
        this.value = value;
    }
}

全部评论

相关推荐

kyw_:接好运
点赞 评论 收藏
分享
10-25 00:32
香梨想要offer:感觉考研以后好好学 后面能乱杀,目前这简历有点难
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务