The beauty of programming: deleting a node from a single-chain table without headers.

Source: Internet
Author: User

1. Problem Description

Suppose there is a single-chain table without a header pointer. A pointer points to a node (not the first or the last) in the middle of the single-chain table. Delete the node from the single-chain table.

As shown in:

In this case, we all know that we can copy data and next of the next node to the current node, set next of the current node to the next node, and then release the memory occupied by the next node (free ),

If the red text condition is removed:

There is a problem with the above method. Generally, the code of the above method is as follows:

void DeleteRandomNode(Node* pCurrent){     if(pCurrent == NULL)            return;     Node* pNext = pCurrent->next;     
     if(pNext == NULL)
     {
// Indicates that the current node is the last Node
Pcurrent = NULL; // if this is the last node, the current pointer is set to null. These statements are incorrect!
     }     pCurrent->data = pNext->data;     pCurrent->next = pNext->next;          delete pNext; }

The red comment illustrates the problem: Setting pcurrent to null does not change the next value of the previous node of the current node, because the next value of the previous node stores the node address pointed to by pcurrent.

Simply put, pcurrent only saves a memory address, and sets pcurrent to null without changing the next value of the previous node. If the current node is the last node, the next value of the previous node should be null, but obviously the above method cannot meet this requirement. Therefore, the problem cannot be solved through the above method after the red-letter condition is removed.

Ah

The beauty of programming: deleting a node from a single-chain table without headers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.