题目

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/merge-two-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ::: image.png

代码

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode() {}
  7. * ListNode(int val) { this.val = val; }
  8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  9. * }
  10. */
  11. class Solution {
  12. public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
  13. if(list1 == null){
  14. return list2;
  15. }
  16. if(list2 == null){
  17. return list1;
  18. }
  19. ListNode l1 = list1; //链表1指针
  20. ListNode l2 = list2; //链表2指针
  21. ListNode head = new ListNode(0); //建立哨兵结点,当作伪头
  22. ListNode curr = head; //伪头指针
  23. while(l1 != null && l2 != null){ //两个链表指针皆不为空
  24. if(l1.val < l2.val){
  25. ListNode newNode = new ListNode(l1.val);
  26. curr.next = newNode;
  27. l1 = l1.next;
  28. curr = curr.next;
  29. }else{
  30. ListNode newNode = new ListNode(l2.val);
  31. curr.next = newNode;
  32. l2 = l2.next;
  33. curr = curr.next;
  34. }
  35. }
  36. if(l1 == null){ //此时两链表必有其一为空
  37. curr.next = l2;
  38. }else{
  39. curr.next = l1;
  40. }
  41. return head.next;
  42. }
  43. }