In: Computer Science
class nodeType // class used to implement a node
{
public:
int data; // data member of node
nodeType * next; // pointer member of node
};
int main()
{
int x;
nodeType * head =________ ; // initialize head pointer
nodeType * tail = _______ ; // initialize tail pointer
_______ * p; // create an auxiliary pointer to a node
for (x = 0; x < 10; ++x)
{
p = _________ nodeType; // create a node
___________ = x + 10; // store a number in the node's data member
p->next = ______ ; // connect the node to the list
if (x == 0)
tail = _______ ;
head = ______ ;
}
return 0;
}
In case of any query do comment. Please rate answer. Thanks
Modified Code:
class nodeType // class used to implement a node
{
public:
int data; // data member of node
nodeType * next; // pointer member of node
};
int main()
{
int x;
nodeType * head =new nodeType ; // initialize head pointer
nodeType * tail = new nodeType ; // initialize tail pointer
nodeType * p; // create an auxiliary pointer to a node
for (x = 0; x < 10; ++x)
{
p = new nodeType; // create a node
p->data = x + 10; // store a number in the node's data member
p->next = head ; // connect the node to the list with head pointer
if (x == 0)
tail = p ; //make tail as first node
head = p; //add newly added node as head node
}
return 0;
}
Explanation:
initialize head & tail pointer with new node object
nodeType * head =new nodeType ;
nodeType * tail = new nodeType ;
For auxiliary pointer:
nodeType * p;
To create new node object use new keyword as below:
p = new nodeType;
store number in data member using -> notation of auxiliary pointer p
p->data = x + 10;
now connect the node p with head of the list:
p->next = head ;
if it is first node then set the tail as first node:
if (x == 0)
tail = p ; //make tail as first node
then make newly added node as head node
head = p;
====================example code to display the functionality=====================
#include<iostream>
using namespace std;
class nodeType // class used to implement a node
{
public:
int data; // data member of node
nodeType * next; // pointer member of node
};
int main()
{
int x;
nodeType * head =new nodeType ; // initialize head pointer
nodeType * tail = new nodeType ; // initialize tail pointer
nodeType * p; // create an auxiliary pointer to a node
for (x = 0; x < 10; ++x)
{
p = new nodeType; // create a node
p->data = x + 10; // store a number in the node's data member
p->next = head ; // connect the node to the list with head pointer
if (x == 0)
tail = p ; //make tail as first node
head = p; //add newly added node as head node
}
while(p->next != NULL){
cout << p->data << endl;
p = p->next;
}
return 0;
}
output: