aawhite
aawhite

Reputation: 33

linked list insertion, pointer confusion

I've looked around the forums but cant seem to find an answer to this very general question. The class below is a basic singly linked list with pushBack written the standard way.

class linkedList {
    private:
        typedef struct node {
                int data;
                struct node *next;
                node(int d):data(d), next(NULL){}
        }*nodePtr;

        nodePtr head, temp, curr;

    public:
        linkedList():head(NULL), temp(NULL), curr(NULL){}

        void pushBack(int d) { 
            temp = new node(d);
            curr = head;
            if (curr != NULL) {
                while (curr->next != NULL) {
                    curr = curr->next;
                }
                curr->next = temp;
            } else head = temp;
        }

        void printAll() {
            curr = head;
            cout << "list:" << endl;
            while (curr) {
                cout << curr->data << " ";
                curr = curr->next;
            }
            cout << endl;
        }
};

but why cant my pushBack function be written like this?

void pushBack(int d) {
        temp = new node(d);
        curr = head;
        while (curr != NULL) {
                curr = curr->next;
        }
        curr = temp;
}

It should iterate through the list until curr == NULL and then set curr = temp. If the list is empty then it doesnt enter the loop and head will be set to the new node by setting temp to curr (which its self is set to head).

The logic makes perfect sense to me so it must be something else I'm missing.

Thank you for the help!

Upvotes: 0

Views: 172

Answers (1)

Valkyrie
Valkyrie

Reputation: 140

your function would fail for the first insertion or pushback, i.e, when the head pointer is null to begin with. when you assign head to curr like this:

curr = head;

curr now points to head and not vice versa .When curr is then assigned temp( i.e. when the first node isnserted into this linked list) , you have only reassigned the pointer curr with the location held by temp. Now all you have is a pointer curr pointing to the same location as temp, both of which pointers are not connected to head pointer at all!

a modified version of your code that would work is:

void pushBack(int d)
{

  temp = new node(d);
  curr = head;
    if(curr!=NULL)
    {
       while (curr != NULL) 
       {
          curr = curr->next;
       }
        curr = temp;
    }
    else head=temp;
}


Upvotes: 2

Related Questions