https://leetcode.com/problems/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 1 -> 2 -> 3 -> 4
is and you were given the third node with value 3
, the linked list should become 1 -> 2 -> 4
a Fter calling your function.
Problem Solving Ideas:
Only the current node is given, to be deleted. The method is to assign the value of the subsequent node to the current node, and then delete the latter node. Because the main purpose is to be familiar with C + +, there are some discussions.
/* * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * * * class Solution {public: void deletenode (listnode* node) { int temp = node->next->val; Node->next->val = node->val; Node->val = temp; Node->next = Node->next->Next;} };
First of all, in fact there is no need to exchange values, only need to assign the value. So two lines would be fine.
/* * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * * * class Solution {public: void deletenode (listnode* node) { node ->val = node->next->val; Node->next = Node->next->Next;} };
Also, in C + +, pay attention to freeing up memory. You can add delete.
There's something simpler.
/* * * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x): Val (x), Next (NULL) {} *}; */ class public : void deletenode (listnode* node) { *node = * (Node->next); // node->next = node->next-> Next;
Why is that OK? Node is a pointer that stores a memory address, so the meaning of the * is the value corresponding to the node memory address. *node=* (Node->next) can directly overwrite the value of the memory address of node as Node->next, so that the memory can be rewritten directly! What's the difference between thinking about Java? Any variable in Java is actually a pointer, but it can only change its direction, not directly change the value he points to that memory. For example, Objecta = B, is to point A to B, but the original a point to the value of the memory, you can not change in any case, this C + + with * is completely possible.
Delete Node in a Linked List