有序链表基础和面试题

有序链表的构造

class ListNode{
    int val;
    ListNode nextNode;
        // 构造函数
    ListNode(int val){
        this.val=val;
        this.nextNode=null;
    }
}

    public static ListNode buildListNode(int [] list){
                 //创建3个临时的ListNode
        ListNode first=null,last=null,newNode;
        for(int i=0;i<list.length;i++){
            newNode=new ListNode(list[i]);
            if(first==null){
                first=newNode;
                last=newNode;
            }else{
                last.nextNode=newNode;
                last=newNode;
            }
        }
        return first;
    }

有序链表的简单打印:

int[] a=new int[]{1,5,6};
ListNode alist=buildListNode( a);

        ListNode testnode = alist;
        while(testnode != null) {
            System.out.println("-->" + testnode.val);
            testnode=testnode.nextNode;
        }
-->1-->5-->6

面试题1:

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        if (l1 == null) return l2;
        if (l2 == null) return l1;

        ListNode head = null;
        if (l1.val <= l2.val){
            head = l1;
            head.next = mergeTwoLists(l1.next, l2);
        } else {
            head = l2;
            head.next = mergeTwoLists(l1, l2.next);
        }
        return head;

    }
}

猜你喜欢

转载自blog.51cto.com/devops2016/2310784