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

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

解答

  1. /**
  2. * Definition for singly-linked list.
  3. * function ListNode(val, next) {
  4. * this.val = (val===undefined ? 0 : val)
  5. * this.next = (next===undefined ? null : next)
  6. * }
  7. */
  8. /**
  9. * @param {ListNode} list1
  10. * @param {ListNode} list2
  11. * @return {ListNode}
  12. */
  13. var mergeTwoLists = function(list1, list2) {
  14. let first = null,
  15. pre = first,
  16. point1 = list1,
  17. point2 = list2;
  18. while (point1) {
  19. if (point2) {
  20. if (point1.val <= point2.val) {
  21. if (first === null) {
  22. first = point1;
  23. }
  24. if (pre) {
  25. pre.next = point1;
  26. }
  27. pre = point1;
  28. point1 = point1.next;
  29. } else {
  30. if (first === null) {
  31. first = point2;
  32. }
  33. if (pre) {
  34. pre.next = point2;
  35. }
  36. pre = point2;
  37. point2 = point2.next;
  38. }
  39. } else {
  40. if (first === null) {
  41. first = point1;
  42. }
  43. if (pre) {
  44. pre.next = point1;
  45. }
  46. pre = point1;
  47. point1 = point1.next;
  48. }
  49. }
  50. while (point2) {
  51. if (first === null) {
  52. first = point2;
  53. }
  54. if (pre) {
  55. pre.next = point2;
  56. }
  57. pre = point2;
  58. point2 = point2.next;
  59. }
  60. return first;
  61. };