Hi, i have this code but i really need some help in understanding it because i r
ID: 3641352 • Letter: H
Question
Hi, i have this code but i really need some help in understanding it because i really dont understand how pointers work. A detailed explanation would be better thank you in advance!#include <iostream>
#include "malloc.h"
#include <cstdio>
using namespace std;
struct node//we create a struct node (class/list)
{
int data;//the struct node will have int as data type
struct node *next;// create reference to the next node
};
int main()
{
int size1,size2,i, num;//here we initialize our variables to integers
struct node *ptr,*ptr2,*result,*temp;
struct node * concat(struct node *,struct node *);
void display(struct node *);
void add(struct node **,int );
ptr=NULL;
ptr2 =NULL;
result=NULL;
temp=NULL;
cout << "enter the size of 1st list"<<endl;
cin>>size1;
cout << "enter the elements" <<endl;
for(i=1;i<=size1;i++)
{
cin>>num;
add(&ptr,num);
}
cout<< "enter the size of 2st list"<<endl;
cin>>size2;
cout<< "enter the elements"<<endl;
for(i=1;i<=size2;i++)
{
cin>>num;
add(&ptr2, num);
}
result = concat(ptr,ptr2);
cout << "the elements in concatenated list are as follows"<< endl;
display(result);
}
// add an node to the list
void add(struct node **q,int num)
{
struct node *temp;
temp = *q;
if(*q==NULL)
{
*q=(node*)malloc(sizeof(struct node));
temp = *q;
}
else
{
while((temp->next)!=NULL)
{
temp=temp->next;
}
temp->next =(node *) malloc(sizeof(struct node));
temp=temp->next;
}
temp->data = num;
temp->next = NULL;
}
// display the elements in the list
void display(struct node *pt)
{
while(pt!=NULL)
{
printf(" %d ",pt->data);
pt=pt->next;
}
}
// concatenation of lists
struct node *concat(struct node *p, struct node *q)
{
struct node *x,*r;
if(p==NULL)
r=q;
if(q==NULL)
r=p;
else
{
x=p;
r=x;
while(x->next!=NULL)
x=x->next;
x->next=q;
}
return(r);
}
Explanation / Answer
A pointer is a location in memory on your computer. When the program runs, it allocates space in the memory for everything. The pointer to a memory location will contain a value in this case a linked node. The value will have the current value in that memory location and a pointer to the next memory location. So when you allocate space for the head pointer, it points to the next node's value. In turn the pointer then points to the next nodes value. So a quick glance over the code, it asks how many linked items would you like to have and then asks you to enter the elements. As you type the number or node into the input, the add function creates a node in the linked list and tells a node's next to point to the memory location of the next node's value. Take a look at this for a better reference: http://en.wikipedia.org/wiki/Linked_list
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.