[JavaScript] Delete intermediate nodes

Delete intermediate node

Implement an algorithm to delete a node in the middle of the singly linked list (except for the first and last nodes, not necessarily intermediate nodes), assuming that you can only access the node.

Example:

Input: node c in the singly linked list a->b->c->d->e->f
Result: no data is returned, but the linked list becomes a->b->d->e->f
Question source: Likou

Under normal circumstances, we want to delete a node in the linked list. The operation is to modify the next element of the previous element; but in this question, we can only access the node to be deleted, so we can delete the node of the next node Take the value over and overwrite the value to be deleted, and then point the next node of the node to be deleted to the next node, which is equivalent to deleting the node in disguise.
 solution:

/**
 * 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) {
    
    
    node.val = node.next.val;
    node.next = node.next.next;
};

Complexity analysis:
Time complexity: O(1)
Space complexity: O(1)

Guess you like

Origin blog.csdn.net/weixin_42345596/article/details/104864441