一、题目内容

image.png

二、题解

解法1:

思路

代码

  1. public class Solution {
  2. public ListNode Merge(ListNode list1, ListNode list2) {
  3. if (list1 == null && list2 == null) {
  4. return null;
  5. }
  6. if (list1 == null) {
  7. return list2;
  8. }
  9. if (list2 == null) {
  10. return list1;
  11. }
  12. ListNode head = new ListNode(0);
  13. ListNode ans = head;
  14. ListNode p = list1;
  15. ListNode q = list2;
  16. while (p != null & q != null) {
  17. if (p.val > q.val) {
  18. head.next = q;
  19. q = q.next;
  20. } else {
  21. head.next = p;
  22. p = p.next;
  23. }
  24. head = head.next;
  25. }
  26. if (p == null) {
  27. head.next = q;
  28. }
  29. if (q == null) {
  30. head.next = p;
  31. }
  32. return ans.next;
  33. }
  34. }