# 21.合并两个有序链表

# 题目

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

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/ (opens new window)

# 答案

思路是创建一个起点为当前节点,循环 list1 和 list2 值的大小,并将小的节点设置为当前节点的下一个节点,当前节点右移一格,小的节点右移一格,直到遍历完一个节点为止,最后将剩下的节点挂载到当前节点的下一节点即可。

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
var mergeTwoLists = function(list1, list2) {
  const headNode = new ListNode(-1);
  let currNode = headNode;
  
  while (list1 !== null && list2 !== null) {
    if (list1.val <= list2.val) {
      currNode.next = list1;
      list1 = list1.next;
    } else {
      currNode.next = list2;
      list2 = list2.next;
    }
    currNode = currNode.next;
  }

  // 循环完后至少有一个节点为 null,且另一个是较大的剩余节点,此时直接当前节点指向该节点即可
  currNode.next = list1 === null ? list2 : list1;

  return headNode.next;
};

# 206.反转链表

# 题目

给你单链表的头节点 head,请你反转链表,并返回反转后的链表。

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

链接:https://leetcode-cn.com/problems/reverse-linked-list/ (opens new window)

# 答案

思路在于挨个反转每个节点,考虑反转的情况,我们需要将其中一个节点的 next 指向上一个节点,所以这里需要两个变量来分别记录上一节点和当前节点,需要注意的是我们改变当前节点的 next 前需要提前记录当前节点的 next,否则会丢失当前节点的 next。

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
  let prev = null;
  let curr = head;
  while (curr) {
    // 需要提前记录 curr 的下一个节点,不然覆盖后无法查找了
    const next = curr.next;
    curr.next = prev;
    // 右移一个节点
    prev = curr;
    curr = next;
  }
  return prev;
};