LeetCode Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode p1 = l1;
        ListNode p2 = l2;
        ListNode p = new ListNode(0);
        ListNode ret = p;
        while(p1 != null && p2 != null){
            if(p1.val < p2.val){
                p.next = new ListNode(p1.val);
                p1 = p1.next;
            }else{
                p.next = new ListNode(p2.val);
                p2 = p2.next;
            }
            p = p.next;
        }
        while(p1 != null){
            p.next = new ListNode(p1.val);
            p1 = p1.next;
            p = p.next;
        }
        while(p2 != null){
            p.next = new ListNode(p2.val);
            p2 = p2.next;
            p = p.next;
        }
        return ret.next;
    }
}

猜你喜欢

转载自blog.csdn.net/dongchunjiang123/article/details/84940368