Question

In: Computer Science

(C++) All programs will be included! This lab gives you a little practice with linked lists...

(C++) All programs will be included!

This lab gives you a little practice with linked lists

·Debug insertSorted() and implement sorted() in numberlist.cpp

·Hint: insertSorted() is just missing a few parts. What is in the function can work fine once you add the right code, though you are free to rewrite it

·You need to have main.cpp, numberlist.h and numberlist.cpp in this project, and if you are using Code::Blocks, remember to set the Build Options to indicate you want to use C++11 or later. The expected output for the final program is:

Test driver to check insertSorted() and sorted() methods of NumberList class

Is empty list in ascending order? true

Displaying list first time:

3.9

5.2

Displaying list second time:

3.9

4.6

5.2

8.4

Is list in ascending order? true

3.9

4.6

5.2

8.4

7.1

Is list in ascending order? False

MAIN.CPP

#include <iostream>
#include "numberlist.h"

using namespace std;

int main()
{
    NumberList list;
    cout << "Test driver to check insertSorted() and sorted() methods of NumberList class"
         << endl << endl;

    cout << "Is empty list in ascending order? "
         << boolalpha << list.sorted() << endl;

    list.insertSorted(5.2);
    list.insertSorted(3.9);
    cout << "Displaying list first time: " << endl;
    list.displayList();
    list.insertSorted(8.4);
    list.insertSorted(4.6);
    cout << "Displaying list second time: " << endl;
    list.displayList();
    cout << "Is list in ascending order? "
         << list.sorted() << endl;
    list.appendNode(7.1);
    list.displayList();
    cout << "Is list in ascending order? "
         << list.sorted() << endl;

    return 0;
}

NUMBERLIST.CPP

#include "numberlist.h"
#include <iostream>

using namespace std;

const double NumberList::EPSILON = 0.000001;


// insert so values are in ascending order
void NumberList::insertSorted(double num) {
    ListNode * newNode = new ListNode;
    newNode->value = num;
    newNode->next = nullptr;

    if (num < head->value) {
        newNode->next = head;
        head = newNode;
    }
    // declare outside for loop so we can use iter after the loop
    ListNode * iter = head;
    for (; nullptr != iter->next; iter = iter->next) {
        if (num < iter->next->value) {
            // insert between iter and iter->next
            iter->next = newNode;
            return;
        }
    }
}


/** destructor to free memory for all elements in list */
NumberList::~NumberList()
{
    ListNode * nodePtr, * nextNode;

    nodePtr = head;
    while (nodePtr != NULL) {
        nextNode = nodePtr->next;
        delete nodePtr;
        nodePtr = nextNode;
    }
}

/** display list to console
    rewritten to show similarity to working with arrays */
void NumberList::displayList() const {
    for (ListNode *nodePtr = head;
         nodePtr != NULL;
         nodePtr = nodePtr->next)
        cout << nodePtr->value << endl;
}

void NumberList::insertNode(double num) {
    ListNode * node = new ListNode;
    node->next = head;
    node->value = num;
    head = node;
}

/** add to end of list */
void NumberList::appendNode(double num) {
    // cannot put num into list directly
    // must construct a node
    ListNode *newNode;

    // use this to go through list
    // serves same purpose as loop counter
    // for array processing
    ListNode *nodePtr;

    newNode = new ListNode;
    newNode->value = num;
    // always have to initialize the pointer
    newNode->next = NULL;

    // usually best to handle special cases
    // first
    if (!head) // like (NULL == head)
        head = newNode;
    else {
        nodePtr = head;
        /** should make sure you understand why the condition
            checks nodePtr->next instead of nodePtr */
        while (nodePtr->next)   // same as (nodePtr->head != NULL)
            nodePtr = nodePtr->next;

        // the actual appending
        nodePtr->next = newNode;
    }
}

// delete a value from the list
void NumberList::deleteNode(double num) {
    ListNode * nodePtr;
    ListNode * previousNode;

    // handle special case first
    if (head->value == num) {
        // save pointer to 2nd element
        nodePtr = head->next;
        // free first element's memory
        delete head;
        head = nodePtr;
    }
    else {
        nodePtr = head;

        while (nodePtr != NULL && nodePtr->value != num) {
            previousNode = nodePtr;
            nodePtr = nodePtr->next;
        }

        /** if nodePtr is not at the end of the list,
           (What would that mean?)
           link the previous node to the node after nodePtr,
           then delete nodePtr
           */
        if (nodePtr) {
            previousNode->next = nodePtr->next;
            delete nodePtr;
        }
    }
}

numberlist.h

// a basic linked list class from Gaddis, ch. 17.2
#ifndef NUMBERLIST_H
#define NUMBERLIST_H
// replacing NULL by nullptr -- if you are using Code::Blocks,
// remember to set the build option that you are using C++11 or later

class NumberList
{
    private:
        // adding this for double comparison
        static const double EPSILON;

        struct ListNode {
            double value;
            ListNode *next;
        };
        ListNode * head; //!< points to start of list

    public:
        /** Default constructor */
        NumberList() {
            head = nullptr;
        }
        /** Default destructor */
        ~NumberList();

        // standard list operations
        // add to end of list
        void appendNode(double);
        // inserts in order
        void insertNode(double);
        void deleteNode(double);
        // insert so values are in ascending order
        // NOTE: if we really wanted this, we should remove
        // insertNode() and appendNode()
        // deleteNode() could stay
        void insertSorted(double);
        // returns true if sorted, false if not
        bool sorted() const;

        void displayList() const;
};

#endif // NUMBERLIST_H

Solutions

Expert Solution

The modified code for insert sorted is shown below:
// insert so values are in ascending order
void NumberList::insertSorted(double num) {
    ListNode * newNode = new ListNode;
    newNode->value = num;
    newNode->next = nullptr;

    if (num < head->value) {
        newNode->next = head;
        head = newNode;
    }
    // declare outside for loop so we can use iter after the loop
    ListNode * iter = head;
    for (; nullptr != iter->next; iter = iter->next) {
        if (num < iter->next->value) {
            // insert between iter and iter->next
             ListNode *temp=iter->next;//temporary node to store next node of iter.
            iter->next = newNode;
            newNode->next=temp;
            return;
        }
    }
   // if the num  is largest of all then it will not be inserted in for loop.
   //So,we need to connect it at last and since iter will be at last node currently therefore
   iter->next = newNode
   return; 
}

The code given in the question have some bugs which is get fixed above with the proper comments written.

Bugs Description :-

Inside the for loop i.e. if we need to insert the node in the middle then we need to connect newNode to the next of iter and also previously the node which is iter's next must be point to newNode 's next now.

So,thats the first bug above that we are not connecting the previous next of iter to newNode's next.

And ,also suppose the newNode we need to insert at last.So,it can't get inserted at last inside the for loop.

So,we inserted at the the end of for loop.

Now ,implementation of sorted function.

bool NumberList::Sorted()
{

 ListNode *temp=head;

while(temp->next!=NULL)

{

 if(temp->value>temp->next->value)

return false;

temp=temp->next;

}

return true;

}

In this function we are simply comparing current value with its next value.

If current value is greater than next value then return false.

If we could not find any such case in the list we'll return true


Related Solutions

C++ Progamming This lab gives you a little practice with stacks and queues ·In “stackfib.cpp”, write...
C++ Progamming This lab gives you a little practice with stacks and queues ·In “stackfib.cpp”, write a non-recursive function fib() which: ·Takes a single int parameter n ·Returns the nth Fibonacci number. We will start with fib(0) == fib(1) == 1, then fib(n) = fib(n-1) + fib(n-2) ·To compute this without using recursion, we use a stack to store the numbers we need to compute (1)   Initialize your result to be 0 (2)   Push the parameter n onto the stack (3)   While the...
C++ Linked Lists Practice your understanding of linked lists in C++ by creating a list of...
C++ Linked Lists Practice your understanding of linked lists in C++ by creating a list of songs/artist pairs. Allow your user to add song / artist pairs to the list, remove songs (and associated artist) from the list and be sure to also write a function to print the list! Have fun! Make sure you show your implementation of the use of vectors in this lab (You can use them too ) You MUST modularize your code ( meaning, there...
C++ Linked Lists Don’t you love music? Everyone loves a great song playlist! Practice your understanding...
C++ Linked Lists Don’t you love music? Everyone loves a great song playlist! Practice your understanding of linked lists in C++ by creating list of songs / artist pairs. Allow your user to add song / artist pairs to the list, remove songs (and associated artist) from the list and be sure to also write a function to print the list! Have fun!
C++ Linked Lists Don’t you love music? Everyone loves a great song playlist! Practice your understanding...
C++ Linked Lists Don’t you love music? Everyone loves a great song playlist! Practice your understanding of linked lists in C++ by creating list of songs / artist pairs. Allow your user to add song / artist pairs to the list, remove songs (and associated artist) from the list and be sure to also write a function to print the list! Have fun! Using Vector or Pointer but please write a new code don't copy the one that exist before
In order to practice on Linked Lists, you will implement one from scratch which will allow...
In order to practice on Linked Lists, you will implement one from scratch which will allow you to examine how they work and explore their capabilities and limitations. You will build a doubly-circular linked list. In doubly linked lists, each node in the list has a pointer to the next node and the previous node. In circular linked lists, the tail node’s next pointer refers to the head and the head node’s previous pointer refers to the tail rather than...
C++ language or Python. Linked Lists You are given a linked list that contains N integers....
C++ language or Python. Linked Lists You are given a linked list that contains N integers. You are to perform the following reverse operation on the list: Select all the subparts of the list that contain only even integers. For example, if the list is {1,2,8,9,12,16}, then the selected subparts will be {2,8}, {12,16}. Reverse the selected subpart such as {8,2} and {16,12}. The list should now be {1,8,2,9,16,12}. Your node definition should consist of 2 elements: the integer value...
11.10 LAB: All permutations of names PLEASE ANSWER IN C++! Write a program that lists all...
11.10 LAB: All permutations of names PLEASE ANSWER IN C++! Write a program that lists all ways people can line up for a photo (all permutations of a list of strings). The program will read a list of one word names (until -1), and use a recursive method to create and output all possible orderings of those names, one ordering per line. When the input is: Julia Lucas Mia -1 then the output is (must match the below ordering): Julia...
6.9 Lab: Singly-Linked Lists As an entry-level programmer you have to be able to read, understand...
6.9 Lab: Singly-Linked Lists As an entry-level programmer you have to be able to read, understand existing code and update it (add new features). One of this assignment’s goals is to read about 400 lines of code in five files, compile and run the program, understand it, and change it as required. Download and review the following files (read code and all comments carefully): College.h College.cpp LinkedList.h LinkedList.cpp main.cpp --------------------------------------------------------- //colleges.txt 3 SBCC Santa Barbara City College; 18524 97 ZZC...
Using C++, you will create a program, where you will create two doubly linked lists. These...
Using C++, you will create a program, where you will create two doubly linked lists. These doubly linked lists will contain integers within them. Using the numbers in both of these linked lists, you add the numbers together, and insert the addition of the two numbers into a singly linked list. the input can be from the user or you just write the input. for example, if one number in the doubly linked list is 817 and in the other...
Working with Linked Lists in C++ Tasks As stated in the objectives, you have two methods...
Working with Linked Lists in C++ Tasks As stated in the objectives, you have two methods to implement. These methods (which contain TODO comments) are found in linked_list.cpp. Part 1 Implement the copy constructor; use the LinkedBag as inspiration for your solution as the technique of creating a deep copy is essentially the same. Part 2 Implement the replace method. //linked_list.cpp #include "linked_list.h" // Header file #include <cassert> template<class Object> LinkedList<Object>::LinkedList() : headPtr( nullptr ), itemCount( 0 ) { }...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT