C++ – How to dynamically create new nodes in linked lists C++

cdata structureslinked listnodes

Could anyone tell me if this is the basic idea of linked lists? What are the pros and cons to this method and what are best practices when implementing linked lists in C++? Im new to data structures so this is my first approach. If there is a better way to do this same thing, please let me know. Additionally, how would you create the nodes dynamically without hard coding it? Thanks.

#include <iostream>
#include <string>

using namespace std;
struct node {
    int x;
    node *next;
};

int main()
{

    node *head;
    node *traverser;


    node *n = new node;                 // Create first node
    node *t = new node;                 // create second node

    head =n;                            //set head  node as the first node in out list.
    traverser = head;                   //we will first begin at the head node.

    n->x = 12;                          //set date  of first node.
    n->next = t;                        // Create a link to the next node

    t->x = 35;                          //define date  of second node.

    t->next = 0;                        //set pointer to null if this is the last node in the list.


    if ( traverser != 0 ) {                 //Makes sure there is a place to start
        while ( traverser->next != 0 ) {
            cout<< traverser->x;            //print out first data member
            traverser = traverser->next;    //move to next node
            cout<< traverser->x;            //print out second data member

        }
    }
    traverser->next = new node;  // Creates a node at the end of the list
    traverser = traverser->next; // Points to that node
    traverser->next = 0;         // Prevents it from going any further
    traverser->x = 42;
}

Best Answer

for tutorial purpose, you can work out this example:

#include <iostream>

using namespace std;

struct myList
{
    int info;
    myList* next;
};

int main()
{
    //Creation part
    myList *start, *ptr;
    char ch = 'y';
    int number;
    start = new myList;
    ptr = start;
    while (ptr != NULL)
    {
        cout << "Enter no. ";
        cin >> ptr->info;
        cout << "Continue (y/n)? ";
        cin >> ch;
        if (ch == 'y')
        {
            ptr->next = new myList;
            ptr = ptr->next;
        }
        else
        {
            ptr->next = NULL;
            ptr = NULL;
        }
    }

    //Traversal part begins
    cout << "Let's start the list traversal!\n\n";
    ptr = start;
    while (ptr!=NULL)
    {
        cout << ptr->info << '\n';
        ptr = ptr->next;
    }
}

It allocates memory dynamically for as many elements as you want to add.

Related Topic