面试题25:合并两个排序的链表

题目:

输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是递增排序的。

分析:

定义两个指针,分别指向这两个链表的第一个结点。当第一个结点的值小于第二个结点的值时,链表1的头结点将是合并后的链表的头结点。继续比较两个头结点,如果第二个结点的值小,链表2的头结点将是合并剩余结点得到的链表的头结点。

解法:

package com.wsy;

class Node {
    private int value;
    private Node next;

    public Node() {
    }

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

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }
}

public class Main {
    public static void main(String[] args) {
        Node head1 = init1();
        Node head2 = init2();
        print(merge(head1, head2));
    }

    public static Node init1() {
        Node node9 = new Node(9, null);
        Node node7 = new Node(7, node9);
        Node node5 = new Node(5, node7);
        Node node3 = new Node(3, node5);
        Node node1 = new Node(1, node3);
        return node1;
    }

    public static Node init2() {
        Node node10 = new Node(10, null);
        Node node8 = new Node(8, node10);
        Node node6 = new Node(6, node8);
        Node node4 = new Node(4, node6);
        Node node2 = new Node(2, node4);
        return node2;
    }

    public static void print(Node node) {
        while (node != null) {
            System.out.print(node.getValue() + "->");
            node = node.getNext();
        }
        System.out.println();
    }

    public static Node merge(Node head1, Node head2) {
        if (head1 == null && head2 == null) {
            return null;
        }
        Node head = null;
        Node current = null;
        while (head1 != null && head2 != null) {
            if (head1.getValue() <= head2.getValue()) {
                if (head == null) {
                    head = current = head1;
                } else {
                    current.setNext(head1);
                    current = current.getNext();
                }
                head1 = head1.getNext();
            } else {
                if (head == null) {
                    head = current = head2;
                } else {
                    current.setNext(head2);
                    current = current.getNext();
                }
                head2 = head2.getNext();
            }
        }
        if (head1 == null) {
            current.setNext(head2);
        } else {
            current.setNext(head1);
        }
        return head;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值