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

95 阅读2分钟

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

删除链表中的节点

请编写一个函数,用于 删除单链表中某个特定节点 。在设计函数时需要注意,你无法访问链表的头节点 head ,只能直接访问 要被删除的节点 。

题目数据保证需要删除的节点 不是末尾节点

输入:head = [4,5,1,9], node = 5
输出:[4,1,9]
解释:指定链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9
输入:head = [4,5,1,9], node = 1
输出:[4,5,9]
解释:指定链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9

提示:

  1. 链表中节点的数目范围是 [2, 1000]
  2. -1000 <= Node.val <= 1000
  3. 链表中每个节点的值都是 唯一 的
  4. 需要删除的节点 node 是 链表中的节点 ,且 不是末尾节点
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} node
 * @return {void} Do not return anything, modify node in-place instead.
 */
var deleteNode = function(node) {

};

解法

由于你无法访问链表的头节点 head ,只能直接访问 要被删除的节点

var deleteNode = function(node) {
    node.val = node.next.val
    node.next = node.next.next
};

反转链表

给你单链表的头节点 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
};