Problem
Implement an algorithm to delete a node in the middle (i.e., any node but the first and last node, not necessarily the exact middle) of a singly linked list, given only access to that node.
Example
Input: the node c from the linked list a->b->c->d->e->f
Output: nothing is returned, but the new linked list looks like a->b->d->e->f
Solution
只给了链表中间待删除的节点指针,要将其从链表中删除。
由于只能访问待删除节点,所以只能将其后的节点往前移动,然后删除最后一个节点。
/**
* 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) {
while(node && node->next)
{
node->val = node->next->val;
if(!node->next->next)
break;
node = node->next;
}
delete node->next;
node->next = NULL;
}
};