Using an appropriate definition of listnode, design a simple linked list class w
ID: 3625515 • Letter: U
Question
Using an appropriate definition of listnode, design a simple linked list class with only two member function and a defult constructor:
void add(double x)
boolean isMumber(double x)
LinkedList();
The add function adds a new node containing x to the front (head) of the list,
while the isMember function tests to see if the list contains a node with the value x. Test your linked list class by adding various numbers to the list and then testing for membership
second part of the question :
Modify your list class of programming challenge 1 to add a copy constructor. Test your class by making a copy of a list and then testing membership on the copy.
third part :
Modify the list class you created in the previous programming challenge to add a print member function. Test the class by starting with an empty list, adding some elements, and then printing the resulting list out.
Explanation / Answer
You usually want to have a node struct defined. Usually, my structs for nodes look something like this:
struct Node
{
int data; // this private variable can be of any type; depends which linked list you want
Node* next; // next pointer for next node in the list
}
You should also have a head pointer and size declared in your .h file along with this struct.
The default constructor for the linked list will define your head pointer. Basically, use a base initialization list (or just initialize) to define. Basically, set your head pointer to NULL at first and your size to 0.
Whenever you want to add something (with your add method), create a new Node pointer (call it temp) and set it to your head pointer. Have your head pointer point to a new node that you're adding in. Make sure to set the data in this node to the double parameter. Then, set the new node's next pointer to the temp pointer. You have successfully added a node to the top of the list. Increment your size. Don't forget to delete the temp pointer to save memory!
For the isMember, you want to walk down the list. Basically, do a for loop:
for (Node* temp = myHead; temp != NULL; temp = temp -> next)
{
// your code here!
}
With this you can walk the list and test if the data value of the node is equal to the parameter. If so, go ahead and return true, and you're done!
Part 2:
The copy constructor is essentially the same as any other data structure. Go ahead and google that one - I really can't tell you how to do it. Basically just copy over all the fields when you do it.
Part 2:
Same as isMember, but as you walk the list, make sure that you're printing the value instead of checking for values. Pretty straightforward - use a cout in the for loop.
Hope this helps! I wanted to avoid giving you exact algorithms.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.