[leetcode] 237. Delete Node in a Linked List解題レポート


タイトルリンク:https://leetcode.com/problems/delete-node-in-a-linked-list/
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) {
        int tem = node->next->val;
        node->next->val = node->val;
        node->val = tem;
        ListNode* q = node->next;
        node->next = q->next;
        delete q;
    }
};