What I want to do:
"Node has two fields: a pointer next and info field [001-999] which holds integer values. Every number in the linked list we will represent as abc(a,b,c digits) where we can access these variables with info.a, info.b, info.c".
I've forgot some parts of OOP (I'll re-read them), but a test is coming up and I don't have time to really read through it now, so I'd be happy, if someone could explain and write/modify my code so it would suit task requirments.
class Node
{
public:
int num;
Node *next;
Node (int n) { num = n; next = NULL; };
}
class List
{
protected:
Node *first, *last;
public:
Node *current;
public:
List () { first = last = current = NULL; };
void add_element (int n);
...
}
void List::add_element (int n)
{
Node *p = new Node (n);
if (first == NULL) first = last = p;
else last = last -> next = p;
current =p;
};
put your two classes as template so that your field can be the data you need like a simple class containing three bitfields that can store values between 0 and 9.
@Ericool
Can you be more specific? I thought that usage of templates are when you have different types of values like float, int, string.
Some example would be nice.
Ericool, your union Data will store just one digit, either a, b, or c. The OP needs to store all 3. And your data is a signed 3-bit value, allowing values of -4 to +3.
I'd keep it simple. Don't use a template because you don't need one for this assignment:
1 2 3 4 5 6 7 8 9 10
class Node
{
public:
int a,b,c; // the 3 digits. a is MSB.
Node *next;
Node (int n) {
next = NULL;
// extract digits on n into a, b and c.
};
}
Maartin, keep it simple: do you need to keep a last pointer? Why not add elements at the head of the list instead of the tail? That way you don't have to worry about maintaining the last pointer. Also why do you have a "current" pointer? Why not have an iterator class if needed. With these simplifications, add_element() becomes trivial:
1 2 3 4 5 6
void List::add_element (int n)
{
Node *p = new Node (n);
p->next = head;
head = p;
};
@dhayden
How can I do " // extract digits on n into a, b and c. " to be precise?
Could u make just a simple example of full program - with 1 example? I'd re-think every line afterwards - just to save up time (test is coming up and besides that, I've 7 different subjects where I've to pass exams, so alot of work ahead of me, haha)
How can I do " // extract digits on n into a, b and c. " to be precise?
Could u make just a simple example of full program - with 1 example?
A full program with 1 example:
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
int main()
{
int value = 951;
int c = value % 10;
int b = value / 10 % 10;
int a = value / 100 % 10 ; // if (guaranteed) value will only be 3 digits, you can skip the mod
std::cout << "a: " << a << ", b: " << b << ", c:" << c << '\n';
}