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.
Subscribe to see which companies asked this question
题目意思:
给定一条链表,和一个结点,要求删除这个结点。比如1 -> 2 -> 3 -> 4
删掉3,变成 1 -> 2 -> 4
这里我们采用一个高效的方法。
1->2->3->4 ,我们可以把 3的值,和4的值交换,然后3的指针域指向,4的指针域指向的地方
/**
* 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) {
if(!node) return;
node->val=node->next->val;
node->next=node->next->next;
}
};