clueless coding // TODO: be smarter

LeetCode 237. Delete Node in a Linked List: C++ Solution

Problem Statement

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Function Signature (C++):
  void deleteNode(ListNode* node)

  Assume we are give this linked list:
    1 -> 2 -> 3 -> 4
  and that we are given access to the node with value 3

  After calling our function, we would want our list to look like this:
    1 -> 2  -> 4

TL;DR Code Solution

void deleteNode(ListNode* node) {
      node->val = node->next->val;
      ListNode* temp = node->next;
      node->next = node->next->next;
      delete temp;