Click here to Skip to main content
15,912,329 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a piece of code of linked list in c++.I want to understand it. I do understand the most of it. But, some parts I do not get. Please explain me that what H->Data does in this code and what p->Next does in this code. Also what does *H and *p do in this. For what i know that pointers hold memory address of other variables.

What I have tried:

#include <stdio.h>
#include <iostream>
#include <time.h>
using namespace std;

struct List
{	int Data;
	List* Next;
};

int main()
{
    List *H, *p;
    srand(time(0));
    cout << "Initial data: ";
    H = new List; p = H;
    H->Data = rand() % 99 + 1;
    cout << H->Data << " ";
    for (int i=0; i<19; i++)
    {
        p->Next = new List;
        p = p->Next;
        p->Data = rand() % 99 + 1;
        cout << p->Data << " ";
    }
    p->Next = NULL;
    
    cout << "\nData of the list: ";
    p = H;
    while (p != NULL)
    {
        cout << p->Data << " ";
        p = p->Next;
    }

    cout << endl;
    system("pause");
    return 0;
}
Posted
Updated 17-Sep-18 16:03pm
Comments
KarstenK 18-Sep-18 2:23am    
Google for some tutorial and examples. You will find A LOT !!!

1 solution

A linked list is what the name implies : a list of objects that are linked together by pointers. In this case, the object is an integer, Data, and the pointer to the next item in the list is Next. The variable H is a pointer to the head of the list. The variable p is a pointer to an item in the list. In the for loop it points to the last item added. In the while loop it points to the current item in the iteration. Items are added to the list by creating a new object and assigning the Next pointer of the last item in the list to this new object. In the while loop you can see how list is chained together through the Next pointer. The pointer p steps through the list, one item at a time, until it encounters a null Next pointer which indicates the last item in the list.

You might want to read up on linked lists in a little more detail : Linked list - Wikipedia[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900