21. Merge Two Sorted Lists

旧城等待, 2022-08-21 04:08 125阅读 0赞

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.

Subscribe to see which companies asked this question

  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. public class Solution {
  10. public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  11. if(l1==null) return l2;
  12. if(l2==null) return l1;
  13. ListNode pre=new ListNode(-1);
  14. ListNode res=pre;
  15. while(l1!=null||l2!=null){
  16. if(l1!=null&&l2!=null){
  17. if(l1.val<l2.val){
  18. pre.next=l1;
  19. l1=l1.next;
  20. }
  21. else{
  22. pre.next=l2;
  23. l2=l2.next;
  24. }
  25. }
  26. else if(l1!=null){
  27. pre.next=l1;
  28. l1=l1.next;
  29. }
  30. else if(l2!=null){
  31. pre.next=l2;
  32. l2=l2.next;
  33. }
  34. pre=pre.next;
  35. }
  36. return res.next;
  37. }
  38. }

发表评论

表情:
评论列表 (有 0 条评论,125人围观)

还没有评论,来说两句吧...

相关阅读