繁体   English   中英

如何通过其持有的数据从链表中删除某个节点?

[英]How to remove a certain node from a linked list by the data its holding?

我们假设输入一个字符串,然后找到该字符串在链表中的位置并删除该节点

当我插入列表的最前面时,我将输入数据值a,b,c,d,而在我打印时将其显示为d,c,b,a。 现在我在它的后面插入,输入f和g,列表现在看起来是d,c,b,a,f,g。 我想删除f,但是它只使用remove函数,但它并不会输出相同的列表

using namespace std;

struct node {
    string data;
    node* next;


};

node* addFront(node* s);
node* addRear(node* s);
void remove(node* head, string abc);
void print(node* head);
int main() {
    node* head = NULL;



    cout << "Enter 5 data strings\n";
    cout << "This will be inserted from the back\n";
    for (int i = 0; i < 5; i++) {
        head = addFront(head);

    }
    print(head);
    cout << "Enter 3 strings and this will be inserted from the back of the orignal string\n";
    for (int i = 0; i < 3; i++) {
        head = addRear(head);
    }
    print(head);
    cout << "Removing the head node\n";
    string n;
    cout << "Enter a string to remove\n";
    cin >> n;
    remove(head, n);
    print(head);
}
node* addFront(node* s)
{
    node* person = new node;
    cin >> person->data;
    person->next = s;
    s = person;

    return s;

}
node *addRear(node*s ) {
    node* person = new node;
    cin >> person->data;
    person->next = NULL;
    if (s == NULL) {
        return person;
    }
    else {
        node* last = s;
        while (last->next != NULL) {
            last = last->next;

        }
        last->next = person;
    }
    return s;



}
void remove(node* head, string a) {

    node* previous = NULL;
    node* current = head;
    if (current == NULL) {
        cout << "Value cannot be found\n";
        return;
    }
    else {
        while (previous != NULL) {
            if (current->data == a) {
                previous->next = current->next;
                delete current;
                break;
            }
            current = current->next;
        }
    }

}
void print(node * head)
{
    node* temp = head;
    while (temp != NULL) // don't access ->next
    {
        cout << temp->data << " ";
        temp = temp->next;
    }
    cout << endl;
}

在remove函数中,当您打while循环时,previous最肯定是NULL。

也许可以考虑做一个do-while循环(更好地处理以前的循环)。

您可能最好以其他方式处理第一个节点,因为前一个节点的持有者实质上是根指针。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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