(java)leetcode-21

    xiaoxiao2021-04-03  31

    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.

    解题思路: 就是拿两个链表组合成一个,这个还是比较简单的直接上代码。

    [java] view plain copy print ? /**  * 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 result = new ListNode(0);          ListNode p = result;          while(l1 != null || l2 != null)          {              if(l1 == null)              {                  p.next = l2;                  break;              }              if(l2 == null)              {                  p.next = l1;                  break;              }              if(l1.val < l2.val)              {                  p.next = l1;                  l1 = l1.next;              }              else              {                  p.next = l2;                  l2 = l2.next;              }              p = p.next;               }          return result.next;      }  }   /** * 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 result = new ListNode(0); ListNode p = result; while(l1 != null || l2 != null) { if(l1 == null) { p.next = l2; break; } if(l2 == null) { p.next = l1; break; } if(l1.val < l2.val) { p.next = l1; l1 = l1.next; } else { p.next = l2; l2 = l2.next; } p = p.next; } return result.next; } }

    转载请注明原文地址: https://ju.6miu.com/read-665980.html

    最新回复(0)