LeetCode-21:Merge Two Sorted Lists

来源:互联网 发布:阿里云盘免费吗 编辑:程序博客网 时间:2024/06/16 11:48

原题描述如下:

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.

Subscribe to see which companies asked this question

题意将两个有序链表合并。

解题思路:两个指针分别指向两个链表,然后比较大小,合并到新链表。

Java代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        
        ListNode headnode = new ListNode(0);
        ListNode node = headnode;
        
        while(l1 != null && l2 != null){
            if(l1.val > l2.val){
                node.next = l2;
                l2 = l2.next;
            }else{
                node.next = l1;
                l1 = l1.next;
            }
            
            node = node.next;
        }
        
        while(l1 != null){
            node.next = l1;
            l1 = l1.next;
            node = node.next;
        }
        
        while(l2 != null){
            node.next = l2;
            l2 = l2.next;
            node = node.next;
        }
        
        return headnode.next;
    }
}
0 0
原创粉丝点击