237. Delete Node in a Linked List
题目:
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 1 -> 2 -> 3 -> 4
and you are given the third node with value 3
, the linked list should become 1 -> 2 -> 4
after calling your function.
思路:
题目只给出了要删除的节点,没有给出前指针或根节点,因此只能利用该节点和其之后的节点实现删除操作。
1.把该节点后一个的节点的值赋给该节点。假如要删除的节点为3,经过赋值操作后为:1->2->4->4
2.删除该节点后一个节点,原节点为:1->2->4
代码:
1 class Solution { 2 public: 3 void deleteNode(ListNode* node) { 4 if (!node || !node->next) { 5 return; 6 } 7 ListNode *nextNode = node->next; 8 node->val = node->next->val; 9 node->next = node->next->next; 10 } 11 };