I am doing a class assignment, where I have to create a linked list representing a big number, but I cant get the print function to work.
This is the code:
Header
class List
{
private:
struct node
{
int data;
node* next;
};
node* head;
node* temp;
node* curr;
public:
List();
void addNode(std::string digits);
void printList();
};
Constructor
List::List()
{
head = NULL;
curr = NULL;
temp = NULL;
}
Function that creates the list
void List::addNode(string digits)
{
int o = 1;
int j = 0;
int i = 0;
node *n;
node *head;
node *temp;
//=================================================================================//
n = new node;
if (digits[0]=='-')
{
n -> data = -1;
head = n;
temp = n;
}
else
{
n -> data = 1;
head = n;
temp = n;
}
//================================================================================//
if ((head->data) == -1)
{
while (o < digits.length())
{
n = new node;
n->data = stoi(digits.substr(o,1));
temp -> next = n;
temp = temp -> next;
o++;
}
}
else
{
while(i < digits.length())
{
n = new node;
n->data = stoi(digits.substr(i,1));
temp -> next = n;
temp = temp -> next;
i++;
}
}
The print function I've been trying to implement, it gives no output (blank):
void List::printList()
{
node* curr = head;
while(curr != NULL)
{
cout<<curr -> data<<" ";
curr = curr -> next;
}
}
The list prints fine when I use this code in the addNode
function:
if ((head -> data) == -1)
{
while(j < digits.length())
{
cout<<head -> data<<" ";
head = head -> next;
j++;
}
}
else
{
while(j<=digits.length())
{
cout<<head -> data<<" ";
head = head -> next;
j++;
}
}
For starters these data members
are redundant. Instead of them you can use similar local variables in member functions of the class if it is required.
The function
addNode
deals with the local variablehead
instead of the data member with the same name.Also you forgot to set the data member next of the last node to
nullptr
.If the member function will be called a second time then there will be memory leaks.
Calling the standard function
std::stoi
for one characteris inefficient.
The class can look the following way as it is shown in the demonstrative program below. You will need to add other required member functions (as for example the copy constructor or destructor) yourself.
The program output is