1.

How To Insert A Node At The End Of Linked List?

Answer»

This CASE is a little bit more complicated. It depends on your implementation. If you have a tail pointer, it’s simple. In case you do not have a tail pointer, you will have to traverse the list till you reach the end (i.e. the NEXT pointer is NULL), then create a new node and MAKE that last node’s next pointer point to the new node.

void InsertNodeAtEnd(INT data)

{

/* 1. create the new node*/

Node *temp = new Node;

temp->data = data;

temp->next = NULL;

/* check if the list is empty*/

if (head == NULL)

{

head = temp;

return;

}

else

{

/* 2. traverse the list till the end */

Node *traveller = head;

while (traveler->next != NULL)

traveler = traveler->next;

/* 3. UPDATE the last node to point to this new node */

traveler->next = temp;

}

}

This case is a little bit more complicated. It depends on your implementation. If you have a tail pointer, it’s simple. In case you do not have a tail pointer, you will have to traverse the list till you reach the end (i.e. the next pointer is NULL), then create a new node and make that last node’s next pointer point to the new node.

void InsertNodeAtEnd(int data)

{

/* 1. create the new node*/

Node *temp = new Node;

temp->data = data;

temp->next = NULL;

/* check if the list is empty*/

if (head == NULL)

{

head = temp;

return;

}

else

{

/* 2. traverse the list till the end */

Node *traveller = head;

while (traveler->next != NULL)

traveler = traveler->next;

/* 3. update the last node to point to this new node */

traveler->next = temp;

}

}



Discussion

No Comment Found