简体   繁体   中英

Insert/Delete Anywhere in a Linked List in C++

I have been learning C++ for a while, and just started looking at linked lists recently. I can construct a template class List with the usual functions insert/remove from back/front. Now I came up with an exercise that asks me to write a function to handle insertions/deletions anywhere in the list.

Please bear in mind that my questions are very basic.

The problem I have is that I see the question as ambiguous. What kind of information does the function require? For instance, for deletion, I can come up with several candidates: 1) delete the first node that has a particular value (argument: value) 2) delete all nodes with a particular value (argument: value) 3) delete a particular node (argument: pointer to that node) 1) and 2) I can easily code. 3) is harder but I can also do it. I just don't see the point in 3). Is it usual to manipulate nodes (outside the list definition) when using lists? As in, is it usual for a program using lists to actually manipulate pointers to the nodes?

What is the usual meaning of "delete anywhere" in this setting?

Similarly, for "insert anywhere", the wording is strange. What does "anywhere" mean? Is the place in the linked list supposed to be given by a particular node?

In linked list you have constant time access to first element. So delete/insert anywhere means the place that exists between first and last element. Basically you need to have 2 iterators. When you find the place you want remove/insert a element, you should refer to the object just before it. because you have not access to the prev element, only to the next one: Let's say our linked list looks like this:
E0->E1->E2->E3->E4

If you want remove E3, you need to have iterator set on E2 so that you could correct pointers for E2->next.

Good reference is the book Standard Library wrote by Nicolai M. Josuttis. The problem you have encountered is widely described there.

node*insert(node*head,int d){

    node*temp=new node;
    temp->data=d;
    if(head==NULL){
        temp->next=NULL;
        head=temp;}
    else 
         {node*curr=head,*pre=NULL;
    while (curr!=NULL && curr->data<temp->data)
    {
        pre=curr;
        curr=curr->next;
    }
    temp->next=curr;
    if(pre==NULL)
        head=temp;
    pre->next=temp;
    }
    return head;
}

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