Implement an algorithm to delete a node in the middle of a singly linked list, given only access to that node.
Example
Linked list is 1->2->3->4
, and given node 3
, delete the node in place 1->2->4
解题思路:
需要注意这里不允许访问之前的节点,所以普通删除办法不可行。
所以删除操作只能朝后面进行,这里将当前节点的后一个节点的值赋给当前节点,这样就可以把当前节点看作是后一个节点,然后把后一个节点删掉即可。
/** * Definition of ListNode * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */ class Solution { public: /* * @param node: the node in the list should be deletedt * @return: nothing */ void deleteNode(ListNode * node) { // write your code here ListNode * post = node->next; node->val = post->val; node->next = post->next; delete post; } };