简体   繁体   中英

Deleting a node in linked list by key, c++

I have a linked list, which contains nodes like this:

struct node
{
    string Language;
    string English;
    node* next;
};

What i want to do is to find a node which has a key Language identical to the one user inputs, delete key Language and also English and, of course, link previous node to the next one. I have no problems with finding, but deleting, and especially linking is really difficult for me. Is there any semi-easy way? Any tips would be much appreciated. Thank you in advance

Assuming you want to delete the second node in a linked list, where root_node is a pointer to the root node and the linked list has a length >= 3:

struct node *A;
struct node *B;
struct node *C;

A = root_node;
B = root_node->next;
C = B->next;

delete B;

A->next = C;

I found nice illustration of deleting a node in a linked list, where the node is neither the head nor tail: 插图

Here is presudo code:

//1. find previous node
node* temp = List->head;
while(temp->next != nodeToDel)
   temp = temp->next
if(temp != null)
//2. skip the node to be delete
temp->next = nodeToDel->next;

//3. delete nodeToDel
delete nodeToDel;

The naive way to delete a node is to attempt to link the previous to the next and then delete the desired node. Instead, you want to copy the next node to the desired node, link the desired node to the next's next, and then delete the next. Say the node matching the user input is N . Then this should work:

// Copy appropriate values
N.Language = (N->next).Language;
N.English = (N->next).English;

// Save pointer to node we need to delete
node* next = N->next;

// Link current node to next's next
N->next = (N->next)->next;

// Next node is useless now, so delete it
delete next;

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