【LeetCode】237. Delete Node in a Linked List

时间:2023-03-09 03:35:27
【LeetCode】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.

提示:

此题主要考察对链表的操作,函数的操作过程如下所示:

【LeetCode】237. Delete Node in a Linked List

  1. 比如我们这里要删除的节点是节点2;
  2. 首先创建一个指向节点3的指针,然后将节点2赋值为节点3,此时的链表状态如第二行所示;
  3. 最后别忘记将节点3删除(通过删除之前创建的指针)。

代码:

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void deleteNode(ListNode* node) {
ListNode *next = node->next;
*node = *next;
delete next;
}
};