Devos Devos - 1 month ago 7
C++ Question

Inserting and finding nodes - Linked Lists in C++

1) I'm still trying to wrap my head around how linked lists work in c++. Currently I'm trying to insert a new node in between other nodes. Although I'm able to add the desired node, anything after that new node seems to be deleted once I print it:

void InsertNode(int pos, int val) {
Node *n = new Node();
n->data = val;

Node *pnt = head;

for (int i = 0; i < pos; i++) {
pnt = pnt->next;
}

pnt->next = n;

DisplayList();
}


2) And then I want to be able to create another operation that can search for an element in the list and output its position (if it exists). However from what I know so far I don't see how I can compare a value that I want to find to an element in a list.

Here's what I'd imagine it would look like, but I know the if statement isn't valid.

void SearchElement(int val) {
Node *list = head;

int i = 0;
while (list) {
list = list->next;
i++;

if (list == val) { cout << "The value is at position: " << i << endl; }
}

//print statement saying it doesn't exist
}

Answer

You have to append the rest of the list to n before you insert the new node:

n->next = pnt->next;
pnt->next = n;

For the second question: Your value is in list->data.

int i = 0;
while (list) {
    if (list->data == val) { 
        cout << "The value is at position: " << i << endl; 
        break; 
    }
    list = list->next;
    i++;        
}