Advertisement
Guest User

Untitled

a guest
Sep 19th, 2019
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  11. ListNode temp = new ListNode(1);
  12. ListNode tail=temp;
  13.  
  14. // 片方が空になるまで
  15. while(l1!=null && l2!=null){
  16. // 値が小さい方の数値をtailにつなげる
  17. if(l1.val <= l2.val){
  18. tail.next = l1;
  19. l1 = l1.next;
  20. }else{
  21. tail.next = l2;
  22. l2 = l2.next;
  23. }
  24.  
  25. // 末尾を更新
  26. tail=tail.next;
  27. }
  28.  
  29. // 一方が空ならば空でないリストをそのままつなげる
  30. if(l1!=null){
  31. tail.next = l1;
  32. } else if(l2!=null){
  33. tail.next = l2;
  34. }
  35.  
  36. return temp.next;
  37. }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement