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 value3
, the linked list should become 1 -> 2 -> 4
after calling your function.
/**
* 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* nextnode=node->next;
node->val = nextnode->val;
node->next = nextnode->next;
//node->next = NULL;
}
};
原本我是想直接复制的:node=node->next;就是用“=”将结构体直接复制,但是出错了,
于是我查询资料发现这样不对,虽然在网上看到有些人用memcpy()函数直接复制,可是这样也不是完全正确的;
下面是我对memcpy()函数的理解,仅供参考。
void * memcpy ( void * dest, const void * src, size_t num );
可知memcpy是复制内存地址,而不是复制具体的值,memcpy会按字节复制,所以如果dest和src所指向的有效内存不一致就会出错