165. Merge Two Sorted Lists【LintCode by java】

Description

Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order.

Example

Given 1->3->8->11->15->null2->null , return 1->2->3->8->11->15->null.

解题:很经典的一道题目,有序链表的合并。LintCode中链表默认没有头指针,不过此题可以构造一个带头结点的链表存放结果,最后返回的时候把头结点去掉即可。代码如下:

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param l1: ListNode l1 is the head of the linked list
     * @param l2: ListNode l2 is the head of the linked list
     * @return: ListNode head of linked list
     */
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // write your code here
        ListNode nhead = new ListNode(0);
        ListNode rear = nhead;
        while(l1 != null && l2 != null){
            if(l1.val < l2.val){
                rear.next = l1;
                l1 = l1.next;
            }else{
               rear.next = l2;
                l2 = l2.next;
            }
            rear = rear.next;
            rear.next = null;
        }
        if(l1 != null){
            rear.next = l1;
        }else{
            rear.next = l2;
        }
        return nhead.next; //关键
    }
}

猜你喜欢

转载自www.cnblogs.com/phdeblog/p/9125097.html