Question

In: Computer Science

C++ Using an appropriate definition of ListNode, design a simple linked list class with only two...

C++

  1. Using an appropriate definition of ListNode, design a simple linked list class with only two member functions and a default constructor:

void add(double x);

boolean isMember(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.

  1. List Copy Constructor Modify your list class of Previous Programming to add a copy constructor. Test your class by making a copy of a list and then testing membership on the copy.
  2. List Print Modify the list class you created in the previous programming challenges 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.
  3. Recursive Member Check Modify the list class you created in the previous programming challenges to use a recursive method to check for list membership. Test your class.
  4. List Member Deletion Modify the list class you created in the previous programming challenges by adding a function to remove an item from the list and by adding a destructor:

        void remove(double x);

       ~LinkedList();

Test the class by adding a sequence of instructions that mixes operations for adding items, removing items, and printing the list.

  1. List Reverse Modify the list class you created in the previous programming challenges by adding a member function for reversing the list:

         void reverse();

The member function rearranges the nodes in the list so that their order is reversed. You should do this without creating or destroying nodes.

Solutions

Expert Solution

Code:

#include <iostream>
using namespace std;

typedef struct ListNode //ListNode structure 
{
    int n;
    struct ListNode* next;  //pointer to next node
    
}ListNode;  //renaming struct ListNode to simply ListNode using typedef keyword

class LinkedList    //LinkedList class
{
public: //the data member and all the two methods have public access i.e any other class methods or functions can use them
    ListNode* head; //head node pointer
    LinkedList()    //null constructor
    {
        head = NULL;    
    }
    void add(double x)  //add method appends a ListNode to the front of LinkedList
    {
        ListNode* tmp = head;   //storing current head in temporary variable
        head = new ListNode;    //declaring dynamic memory using new keyword
        head->n = x;            //assigning the new value to new node
        head->next = tmp;       //adding next pointer to the previous head
    }
    bool isMember(double x) //isMember method returns status of presence of an element in the LinkedList
    {
        ListNode* itr = head;
        while(itr!=NULL)    //iterating through the LinkedList until NULL is attained i.e exiting after last element
        {   
            if(itr->n==x)   //if the current node has the given value then returning true
                return true;
            itr = itr->next;
        }
        return false;   //if no node contains the given value then returning false
    }
};

int main()      //main funtion to test the LinkedList class
{
    LinkedList l;   //declaring static LinkedList variable l
    l.add(4);       //adding 4 to front
    l.add(3);       //adding 3 to front
    l.add(2);       //adding 2 to front
    l.add(1);       //adding 1 to front
    for(ListNode* itr = l.head; itr!=NULL; itr = itr->next) //printing all LinkedList node elements to screen in order of list
        printf("%d -> ", itr->n);
    printf("null\n");
    printf("Is 3 a member of linked list or not(True[1]/False[0]): %d\n", l.isMember(3));   //testing if 3 is present in LinkedList l
    printf("Is 5 a member of linked list or not(True[1]/False[0]): %d\n", l.isMember(5));   //testing if 5 is present in LinkedList l

    return 0;
}

Output:

 #include <iostream> using namespace std; struct node {   double data;    node *next;     node(int data)  {               this->data = data;   } }; class LinkedList {         node *head; public:     LinkedList()    {               head = NULL;    }       LinkedList(LinkedList &copy)        {               copy.head = this->head;      }       void add(double data)   {       //create new node               node *m = new node(data);                               //if list is empty then node is the first element               if (head == NULL)               {                       head = m;                       m->next = NULL;              }               //else add input as first element               else            {                       m->next = head;                      head = m;               }       }       void remove(double key)         {               // Store head node              node *temp = head, *prev;               // If head node itself holds the key to be deleted              if (temp != NULL && temp->data == key)               {                       head = temp->next; // Changed head                           return;                 }               // Search for the key to be deleted, keep track of the          // previous node as we need to change 'prev->next'           while (temp != NULL && temp->data != key)            {                       prev = temp;                    temp = temp->next;           }               // If key was not present in linked list                if (temp == NULL)                       return;                 // Unlink the node from linked list             prev->next = temp->next;  }       bool isMember(double data)      {               node *c = head;                 while (c != NULL)               {                       if (c->data == data)                         {                               break;                  }                       c = c->next;                 }               if (c == NULL)          {                       return false;           }               else                    return true;    }       bool checkMember(double x)      {               return check(head, x);  }       //helper function       bool check(node *elem, double x)        {               if (elem != NULL)               {                       if (elem->data == x)                                 return true;                    else                            return check(elem->next, x);                 }               else                    return false;   }       void reverse()  {               // Initialize current, previous and             // next pointers                node *current = head;           node *prev = NULL, *next = NULL;                while (current != NULL)                 {                       // Store next                   next = current->next;                        // Reverse current node's pointer                       current->next = prev;                        // Move pointers one position ahead.                    prev = current;                         current = next;                 }               head = prev;    }       void Print()    {               node *m = head;                 while (m != NULL)               {                       cout << m->data << " ";                  m = m->next;                 }       }       ~LinkedList()   {               cout << "Destroyed";      }; }; int main() {      LinkedList list;        list.add(20);   list.add(10);   list.add(5);    list.add(3);    list.Print();   list.reverse();         list.remove(3);         list.Print();   LinkedList copy;        copy = list;    cout << "copy:";  copy.Print(); cout<<endl<<list.isMember(5)<<endl;     cout<<list.checkMember(3)<<endl; }

Sample output:


Related Solutions

C++ question: Design and implement your own linked list class to hold a sorted list of...
C++ question: Design and implement your own linked list class to hold a sorted list of integers in ascending order. The class should have member functions for inserting an item in the list, deleting an item from the list, and searching the list for an item. Note: the search function should return the position of the item in the list (first item at position 0) and -1 if not found. In addition, it should have member functions to display the...
Solve this Write a C++ class that implements a stack using a linked list. The type...
Solve this Write a C++ class that implements a stack using a linked list. The type of data contained in the stack should be double. The maximum size of the stack is 30. Implement the following methods: . · Constructor and destructor; // 5 pts · void push (double value); // pushes an element with the value into the stack. 5 pts. · double pop (); // pops an element from the stack and returns its value. 5 pts. ·...
Below is a definition of the class of a simple link list. class Chain; class ChainNode...
Below is a definition of the class of a simple link list. class Chain; class ChainNode { friend class Chain; private: int data; ChainNode *link ; }; class Chain{ public: ... private: ChainNode *first; // The first node points. } Write a member function that inserts a node with an x value just in front of a node with a val value by taking two parameters, x and val. If no node has a val value, insert the node with...
Make in c++ this Programming Challenge 1. Design your own linked list class to hold a...
Make in c++ this Programming Challenge 1. Design your own linked list class to hold a series of integers. The class should have member functions for appending, inserting, and deleting nodes. Don’t forget to add a destructor that destroys the list. Demonstrate the class with a driver program. 2. List Print Modify the linked list class you created in Programming Challenge 1 to add a print member function. The function should display all the values in the linked list. Test...
Using doubly linked list in c++ with class constructor: DNode(){    song = Song();    prev...
Using doubly linked list in c++ with class constructor: DNode(){    song = Song();    prev = NULL;    next = NULL; } DNode(string s, string a, int lenmin, int lensec){    song = Song(s,a,lenmin,lensec);    prev = NULL;    next = NULL; } for each node. Write the method: void moveUp(string t); This method moves a song up one in the playlist. For instance, if you had the following: Punching in a Dream, The Naked And Famous................3:58 Harder To...
(using single linkedlist c++)In this assignment, you will implement a Polynomial linked list(using single linkedlist only),...
(using single linkedlist c++)In this assignment, you will implement a Polynomial linked list(using single linkedlist only), the coefficients and exponents of the polynomial are defined as a node. The following 2 classes should be defined. p1=23x 9 + 18x 7+3 1. Class Node ● Private member variables: coefficient (double), exponents (integer), and next pointer. ● Setter and getter functions to set and get all member variables ● constructor 2. Class PolynomialLinkedList ● Private member variable to represent linked list (head)...
(Write a C# program DO NOT USE CLASS)Implement the merge sort algorithm using a linked list...
(Write a C# program DO NOT USE CLASS)Implement the merge sort algorithm using a linked list instead of arrays. You can use any kind of a linked structure, such as single, double, circular lists, stacks and/or queues. You can populate your list from an explicitly defined array in your program. HINT: You will not be using low, middle and high anymore. For finding the middle point, traverse through the linked list while keeping count of the number of nodes. Break...
1) a. Write down a C++ program which will create a list (simple linear linked list)...
1) a. Write down a C++ program which will create a list (simple linear linked list) of nodes. Each node consists of two fields. The first field is a pointer to a structure that contains a student id (integer) and a gradepoint average (float). The second field is a link. The data are to be read from a text file. Your program should read a file of 10 students (with student id and grade point average) and test the function...
I've provided a Node class that implements a node of a simple singly-linked list (with .value...
I've provided a Node class that implements a node of a simple singly-linked list (with .value and .next fields), and an empty LinkedList class. Your task is to implement LinkedList.sort(l), where given the node l as the head of a singly-linked list, LinkedList.sort(l) sorts the nodes in the list into ascending order according to the values in the .value field of each node. Your implementation should do an in-place update of the list. It is ok to use a simple...
Write a C++ program that design a class definition to be put in a header file...
Write a C++ program that design a class definition to be put in a header file called fizzjazz.h A store sells online FizzJazz which are sound tones made by famous bands. For each FizzJazz, the store wants to keep track of the following attributes: * title - the name of the sound tone * band - Famous band name that created the tone * duration - this is in seconds and may be fractional: examples: 20.0, 34.5 Each attribute will...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT