leetcode面试题——面试题25. 合并两个排序的链表

面试题25. 合并两个排序的链表
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
示例1:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
限制:
0 <= 链表长度 <= 1000
解题思路:设置一个虚拟头结点,分别用两个指针比较,数据小的插入新的链表,然后指针后移,新链表的当前指针同样后移,重复上述操作。最后进行细节操作。

/**
 * 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 newNode = new ListNode(0);
        ListNode cur = newNode;
        while(l1 != null && l2 != null){
            if(l1.val > l2.val)
            {
                cur.next = l2;
                l2 = l2.next;
            }else{
                cur.next = l1;
                l1 = l1.next;
            }
            cur = cur.next;
        }
        if(l1 != null){
            cur.next = l1;
        }
        if(l2 != null){
            cur.next = l2;
        }
        return newNode.next;
    }
}
发布了2 篇原创文章 · 获赞 0 · 访问量 11

猜你喜欢

转载自blog.csdn.net/qq_40860196/article/details/104696226
今日推荐