Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
supposed the linked list Is 3
, the linked list should become 1, 2-4
after calling your function.
[Idea] only knows the current node, to delete the current node. Unlike the usual deletions, we don't know the previous node.
We can use the current node to contact the previous node to copy the latter node. Then delete the latter node, which is equivalent to implementing the delete operation.
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public: void Deletenode (listnode* node) { if (node = = nullptr) return; ListNode *next = node->next; Node->val = node->next->val; Node->next = next->next; Delete next;} ;
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode] Delete Node in a Linked List