题目:
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 value 3
,
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* front,*rear;
//rear指向front后面一个结点
front = node;
rear = front->next;
//front和rear同步后移,每次都把rear的值赋给front
//一直将rear移动到最后一个结点
while(rear->next != NULL)
{
front->val = rear->val;
rear = rear->next;
front = front->next;
}
//此时最后一次把rear的值赋值给front,rear就成了多余的那个结点。
front->val = rear->val;
delete rear;
front->next = NULL;
}
};