LeetCode-合并两个有序链表

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zlp_zky/article/details/82355801

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

示例:

输入:1->2->4, 1->3->4
输出: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 temp1=l1;
           ListNode temp2=l2;
           ListNode lc=new ListNode(0);
           ListNode tem=lc;
        while (temp1!=null&&temp2!=null){
            if (temp1.val<temp2.val){lc.next=temp1;lc=temp1;temp1=temp1.next;
            }else if (temp1.val>temp2.val){
                lc.next=temp2;lc=temp2;temp2=temp2.next;
            }else if (temp1.val==temp2.val) {
                lc.next=temp1;lc=temp1;temp1=temp1.next;
                lc.next=temp2;lc=temp2;temp2=temp2.next;
            }

        }
        lc.next=temp1!=null?temp1:temp2;
        return tem.next;
    }
}

猜你喜欢

转载自blog.csdn.net/zlp_zky/article/details/82355801