Interview questions 02.03. Delete intermediate node

topic:

Implement an algorithm to remove a node in the middle of a one-way linked list (except for the first and last node, it is not necessarily an intermediate node), assuming that you can only access the node.

 

Example:

Input: one-way linked list a-> b-> c-> d-> e-> c in node f
Results: No data is returned, but this list becomes a-> b-> d-> e-> f

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/delete-middle-node-lcci
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Problem-solving ideas:

To delete a node, you can put the value of the next node of the node assigned to the node, at which point the next node acts as a node, let the next node points to the next node of a next node, this time, is equivalent to the original node the next node discarded

Code:

/**
 * 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) {
        node->val=node->next->val;
        node->next=node->next->next;
    }
};

 

Published 253 original articles · won praise 15 · views 30000 +

Guess you like

Origin blog.csdn.net/junjunjiao0911/article/details/105181222