Learning C++ – Linked List – addNextItem

Youtube is full of “Everyone needs to know how to code” so I try to learn some basics in c++, but it’s in the beginning, I hope I will make use of it in my Raspberry Pi MiniProjects

struct node {
int data ;
node *next ;
} ;

void linkedListDisplay(node *start){
    int i = 0 ;
    while (start!=NULL){
        i++ ;
        cout << i << ":" << start->data << endl ;
        start = start->next ;
    }
}

node *initLinkedList(){
    node *ptr = new node ;
    ptr->data = 10 ;
    ptr->next = NULL ;

    return ptr;
}

node *addNextItem(node *previous_addr, int &dataInput){
    node *ptr = previous_addr ;

    node *newItem = new node ;
    newItem->data = dataInput ;
    newItem->next = NULL ;
    ptr->next = newItem ;

    return newItem ;
}

int main()
{
    node *head = initLinkedList() ;
    node *t = head ;
    node *next ;

    int value ;
    cout << "Please input a number: " ;
    cin >> value ;
    next=addNextItem(t, value) ;
    t=next ;
    
    cout << "Please input a number: " ;
    cin >> value ;
    next=addNextItem(t, value) ;
    t=next ;

    linkedListDisplay(head) ;

    return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s