来一起刷简单算法题[八] 链表

222 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第15天,点击查看活动详情

反转链表

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

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

提示:

  • 链表中节点的数目范围是 [0, 5000]
  • -5000 <= Node.val <= 5000
/**
 * 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) {
    
};

栈的特点是先进后出,可以利用这个特性来实现反转

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
    const stack = []
    let current = head
    while(current !== null) {
        stack.push(current)
        current = current.next
    }
    // 如果链表为空
    if (!stack.length) {
        return null
    }
    // pop出来当 head
    let node = stack.pop()
    let dummy = node
    while(stack.length) {
        node.next = stack.pop()
        node = node.next
    }
    // 最后的next要设置为空,不然要导致成环
    node.next = null
    return dummy
};

双链表

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
    let newListNode = null
    while(head !== null) {
      // 先把下一个节点保存起来
      const temp = head.next
      // 把下一个节点设置成新的链表
      head.next = newListNode
      // 把新的链表设置成修改后的节点
      newListNode = head
      // 链表后移
      head = temp  
    }
    return newListNode
};

合并两个有序列表

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

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

提示:

  • 两个链表的节点数目范围是 [0, 50]
  • -100 <= Node.val <= 100
  • l1 和 l2 均按 非递减顺序 排列
/**
 * 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) {
    
};

循环判断法

因为链表是升序的,我们只需要遍历每个链表的头,比较一下哪个小就把哪个链表的头拿出来放到新的链表中,一直这样循环,直到有一个链表为空,然后我们再把另一个不为空的链表挂到新的链表中。

iShot2022-03-28 16.56.46.png

iShot2022-03-28 16.57.22.png

/**
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
var mergeTwoLists = function(list1, list2) {
  let dummy = new ListNode(0)
  let current = dummy
  if (!list1) return list2
  if (!list2) return list1
  while (list1 && list2) {
    if (list1.val < list2.val) {
      current.next = list1
      list1 = list1.next
    } else {
      current.next = list2
      list2 = list2.next
    }
    current = current.next
  }
  current.next = list1 || list2
  return dummy.next
};

递归

var mergeTwoLists = function(list1, list2) {
  if (!list1) return list2
  if (!list2) return list1
  if (list1.val < list2.val) {
      list1.next = mergeTwoLists(list1.next, list2)
      return list1
  } else {
      list2.next = mergeTwoLists(list1, list2.next)
      return list2
  }
};