一、问题描述
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:
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.
二、解题思路
第一种方法:给的是链表头结点:可以从头结点开始遍历到要删除结点的前一个结点,然后该结点指向要删除结点的下一个结点,删除要删除的结点,复杂度O(n)
第二种方法:给的是要删除结点:对于非尾结点,将下个结点的内容复制到本结点,在删除掉下一个结点即可(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) {
if(node == NULL) return;
//pnext指向要删除结点的下一个结点
ListNode* pnext = node->next;
//把结点的值赋值给要删除的这个节点
node->val = pnext->val;
//把结点的下一个指向赋值给要删除的结点
node->next = pnext->next;
//经过上面两步,已经把要删除结点的下一个结点完全copy到当前的结点了
//所以,删除掉下一个结点就行了
delete pnext;
}
};