剑指Offer【25、合并两个排序的链表】

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

递归的思想

public static ListNode merge(ListNode list1, ListNode list2) {
    if (list1 == null) {
        return list2;
    }
    if (list2 == null) {
        return list1;
    }

    ListNode head = null;

    if (list1.getnValue() < list2.getnValue()) {
        head = list1;
        head.setpNext(merge(list1.getpNext(), list2));
    } else {
        head = list2;
        head.setpNext(merge(list1, list2.getpNext()));
    }

    return head;
}
public class ListNode {
    private int nValue;
    private ListNode pNext;

    public int getnValue() {
        return nValue;
    }

    public void setnValue(int nValue) {
        this.nValue = nValue;
    }

    public ListNode getpNext() {
        return pNext;
    }

    public void setpNext(ListNode pNext) {
        this.pNext = pNext;
    }

    public static ListNode createList(int[] arr) {
        if (arr.length == 0) {
            return null;
        }
        ListNode head = new ListNode();
        ListNode currentNode = head;
        for (int i = 0; i < arr.length-1; i++) {
            currentNode.nValue = arr[i];
            currentNode.pNext = new ListNode();
            currentNode = currentNode.pNext;
        }
        currentNode.nValue = arr[arr.length-1];
        currentNode.pNext = null;
        return head;
    }

    public static void printList(ListNode listNode) {
        StringBuffer buf = new StringBuffer("[");
        ListNode currentNode = listNode;
        while (currentNode != null) {
            buf.append(currentNode.nValue).append(",");
            currentNode = currentNode.getpNext();
        }
        String result = buf.length() == 1?buf.toString():buf.substring(0, buf.length()-1);
        System.out.println(result+"]");
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值