题目描述
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.
题目要求删除链表中的结点,但一般的题目是给定链表的头结点和待删除元素的值,而本题是直接给定被删除的链表元素。
解题代码
因为链表只有next指针而没有Priv指针,所以不能直接通过指针操作实现删除操作,本题可以通过从复制被删除结点之后结点的值,使得最后一个结点变为多余结点,只用删除最后一个结点即可。
/**
* 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* node2 = node->next;
while(node2->next != NULL)
{
node->val = node2->val;
node = node2;
node2 = node2->next;
}
node->val = node2->val;
node->next = node2->next;
delete node2;
}
};