Delete Node in the Middle of Singly Linked List

Description

Implement an algorithm to delete a node in the middle of a singly linked list, given only access to that node.

Example
Given 1->2->3->4, and node 3. return 1->2->4

Lintcode_ladder

Method

  1. x
  2. x

Example

  1. 1
/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param node: a node in the list should be deleted
     * @return: nothing
     */
    void deleteNode(ListNode *node) {
        // Version I
        if (!node) {
            return;
        }
        node->val = node->next->val;
        ListNode* tmp = node->next;
        node->next = node->next->next;
        delete tmp;
        // ------------------------------------
        // Version II
        ListNode* tmp = node->next;
        *node = *tmp;
        // cout << "tmp = " << *tmp << endl; 
        // cout << "node = " << *node << endl; 
        delete tmp;
        //return;
    }
    //operator=()
};

Similar problems

x

Tags

x

results matching ""

    No results matching ""