简体   繁体   中英

Deleting a node in a circular linked list c++?

EDITED: using c++ to code.

void circularList::deleteNode(int x)
{
    node *current;
    node *temp;
    current = this->start;

    while(current->next != this->start)
    {
        if(current->next->value == x)
        {
            temp = current->next;
            current->next = current->next->next;
            delete current->next;
        }
    else{ 
            current = current->next;
             }
    }
}

Added the else i'm sorry i kinda forgot to copy that part of the code and yes it is for learning purposes. I'm new to coding with c++ and probably come off as a noob sorry about that.

Also as for this line of code

this->start->value == x

im not sure what you mean by it or where you think it goes, yes there are nodes in the linked list and assume that it will always have at lease 1 node all the time.

Think about this two lines:

current->next = current->next->next;

delete current->next;

Try to determine what you are actually deleting (no its not current->next; , at least not the one you want to delete).

You never move to the next node in your while loop. After your if, you should have:

else
    current = current->next;

Also, you might want to consider returning from the function after you've found the node (unless you suspect that two nodes have the same value).

In addition to Justin's and Let_Me-Be's answers, consider what you might need to take care of when

this->start->value == x

If you don't handle that right, you'll lose your whole list (or crash trying to get to it)...

Do you have only a singularly linked list?

Have you considered the STL, perhaps a deque ?

Or, if you must have a single linked list then why not take something that it 90% STL (;-) and look at the Boost libraries?

You do seem to be reinventing the wheel here. Why not take some existing - and tested - code and use that?

Is "deleting a node from linked list" the issue or "deleting a node from a circular linked list" the issue?

The difference from non-circular to circular is the line:

while(current->next != this->start)

If the list were non circular it would have been

while(current->next != NULL )

Apart from that, there are issues with the code snippet, which others have already pointed out.

Another thing: Do you check that you have at least one valid node in your list before you call deleteNode?

I ask this as your function does not check for a NULL-value of the start element.

The solution would be to add the line

if(start == NULL) return

as first line of your method to avoid this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM