码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode-21 Merge Two Sorted Lists Solution (with Java)

时间:2020-03-02 15:09:28      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:else   ini   image   for   rip   sort   sts   ted   tail   

1. Description:

技术图片

2. Examples:

技术图片

3.Solutions:

 1 /**
 2  * Created by sheepcore on 2019-05-07
 3  * Definition for singly-linked list.
 4  * public class ListNode {
 5  *     int val;
 6  *     ListNode next;
 7  *     ListNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
12         ListNode head = new ListNode(-1);
13         ListNode p = l1, q = l2, tail = head;
14         while (p != null && q != null){
15             if(p.val <= q.val){
16                 tail.next  = p;
17                 p = p.next;
18                 tail = tail.next;
19             } else{
20                 tail.next = q;
21                 q = q.next;
22                 tail = tail.next;
23             }
24         }
25         if(p != null)
26             tail.next = p;
27         if(q != null)
28             tail.next = q;
29         return head.next;
30     }
31 }

 

LeetCode-21 Merge Two Sorted Lists Solution (with Java)

标签:else   ini   image   for   rip   sort   sts   ted   tail   

原文地址:https://www.cnblogs.com/sheepcore/p/12395165.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!