【LeetCode & 剑指offer刷题】链表题3:18 删除链表中的结点(237. Delete Node in a Linked List)
【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)
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.
Given linked list -- head = [4,5,1,9], which looks like following:
4 -> 5 -> 1 -> 9
Example 1:
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list
should become 4 -> 1 -> 9 after calling your function.
Example 2:
Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list
should become 4 -> 5 -> 9 after calling your function.
Note:
-
The linked list will have at least two elements.
-
All of the nodes' values will be unique.
-
The given node will not be the tail and it will always be a valid node of the linked list.
-
Do not return anything from your function.
/*删除链表中的某一个结点(本题不用考虑尾结点)
通用方法(给的是链表头结点):可以从头结点开始遍历到要删除结点的上一个结点,然后该结点指向要删除结点的下一个结点,删除要删除的结点,不过需花费O(n)
方法2(给的是要删除结点):对于非尾结点,将下个结点的内容复制到本结点,在删除掉下一个结点即可(O(1)),
但是对尾结点,则只能从链表头结点开始遍历到尾结点的前一个结点(O(n))
*/
/**
* 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)
{
// *node = *node->next; //*为取内容运算符,将指针指向的结构体内容复制过去
//真的删除
/* ListNode* temp = node->next;
*node = *temp; //将指针指向的结构体内容复制过去
delete temp; //删除多余的结点*/
if(node == nullptr) return;
ListNode* pnext = node->next; //保存下一个结点指针,以便之后删除
node->val = pnext->val; //复制值
node->next = pnext->next; //复制指针
delete pnext; //掌握
}
};
/*
也可用这个(掌握)
ListNode* pnext = node->next;
node->val = node->next->val;
node->next = node->next->next;
delete pnext;
*/