简体   繁体   中英

Delete a node from a given position in doubly circular linked list

the code is giving a garbage value when i am deleting a node from position between 2 to n-1 in range of 1 to n here is my code for deletefrommiddle:

void deleteatmiddle(node*&head,int k)
{
if(k==1)
{
    deleteathead(head);
    return;
}
else if(k==length(head))
{
    deleteattail(head);
    return;
}
node*temp = head;
    int i=1;
    while(i<k)
    {
        temp=temp->next;
        i++;
    }
    temp->prev->next = temp->next;
    temp->next->prev = temp->prev;
    delete temp;
    return;
}

for example in a list of: 1 2 3 4 if i want to delete element at 2nd position it is giving: 1 624244072 3 4

How confident are you that your original data is okay.

#include <iostream>

using namespace std;

class Node {
public:
    Node() = default;
    Node(int v): value(v) {}

    Node * prev = nullptr;
    Node * next = nullptr;
    int value;

};

void deleteatmiddle(Node*&head,int k)
{
    Node * temp = head;
    int i=1;
    while(i<k)
    {
        temp=temp->next;
        i++;
    }
    temp->prev->next = temp->next;
    temp->next->prev = temp->prev;
    delete temp;
    return;
}

void dump(Node *node) {
    while (node != nullptr) {
        cout << node->value << endl;
        node = node->next;
    }
}

int main(int, char **) {
    Node * head = new Node(1);
    Node * v2 = new Node(2);
    Node * v3 = new Node(3);
    Node * v4 = new Node(4);

    head->next = v2;

    v2->prev = head;
    v2->next = v3;

    v3->prev = v2;
    v3->next = v4;

    v4->prev = v3;

    dump(head);
    deleteatmiddle(head, 2);

    cout << "After." << endl;
    dump(head);
}

Compile and run:

$ g++ Foo.cpp --std=c++17 -o Foo && Foo
1
2
3
4
After.
1
3
4

I simplified the code slightly (got rid of deleting at head / tail) and changed the class name because I like upper case names for classes, but otherwise, this is your code. As you can see, after manually building the linked list and then deleting from the middle, it worked as expected.

This suggests the problem is in the code you haven't shown us.

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