Question

Double linked list implementation of PutItem function. How to fix my code to get desired output b...

Double linked list implementation of PutItem function. How to fix my code to get desired output below:

Output:

2 5 8

#ifndef ITEMTYPE_H
#define ITEMTYPE_H

enum RelationType { LESS, GREATER, EQUAL};

class ItemType
{
public:
    ItemType();
    void setValue(int newValue);
    int getValue() const;
    RelationType ComparedTo(ItemType newItem);

private:
    int value;
};

#endif // ITEMTYPE_H


// ItemType.cpp

#include "ItemType.h"

ItemType::ItemType()
{
    value = 0;
}

void ItemType::setValue(int newValue)
{
    value = newValue;
}

int ItemType::getValue() const
{
    return value;
}

RelationType ItemType::ComparedTo(ItemType newItem)
{
    if (value < newItem.value)
        return LESS;
    else if (value > newItem.value)
        return GREATER;
    else
        return EQUAL;
}


// Dlists.h

#ifndef DLISTS_H
#define DLISTS_H

#include "ItemType.h"

struct NodeType;

class Dlists
{
public:
    Dlists();
    void FindItem(NodeType *head, ItemType item, NodeType *& location, bool &found);
    void PutItem(ItemType item);
    void DeleteItem(ItemType item);
    void Print() const;

private:
    NodeType *head;
    int length;
    NodeType *currentPos;
};

#endif // DLISTS_H

#include "Dlists.h"
#include <iostream>
using namespace std;

struct NodeType
{
    NodeType *next;
    NodeType *prev;
    ItemType info;
};

Dlists::Dlists()
{
    head = nullptr;
    currentPos = nullptr;
    length = 0;
}

void Dlists::Print() const
{
    NodeType *temp = head;
    while (temp != nullptr)
    {
        cout << temp->info.getValue() << " ";
        temp = temp->next;
    }
}

void Dlists::FindItem(NodeType *head, ItemType item, NodeType *&location, bool &found)
{
    bool mts = true;
    location = head;
    found = false;

    while (mts && !found)
    {
        if(item.ComparedTo(location->info) == EQUAL)
            found = true;
        else if (item.ComparedTo(location->info) == LESS)
            mts = false;
        else // greater
        {
            location = location->next;
            mts = (location != nullptr);
        }
    }
}

void Dlists::PutItem(ItemType item)
{
    NodeType *location;
    bool found;

    // create a new node with the item data
    NodeType *newNode;
    newNode = new NodeType;
    newNode->info = item;

    if (length == 0) // if list is empty
    {
        head = newNode;
        newNode->next = nullptr;
        newNode->prev = nullptr;
    }
    else if (length == 1)
    {
        if(item.ComparedTo(head->info) == LESS)
        {
            newNode->prev = nullptr;
            newNode->next = head;
            head->prev = newNode;
            head = newNode;
        }
        else // if item is greater than the sole node
        {
            newNode->prev = head;
            newNode->next = nullptr;
            head->next = newNode;
        }
    }
    else // insertion point is in the middle
    {
        FindItem(head, item, location, found);
        newNode->prev = location->prev;
        newNode->next = location;
        (location->prev)->next = newNode;
        location->prev = newNode;
    }

    // increment the list
    length++;
}


// driver.cpp

#include "Dlists.h"
#include <iostream>
using namespace std;

int main()
{
    Dlists myList;
    ItemType item;

    // Adding 2 to the list
    item.setValue(2);
    myList.PutItem(item);

    // Adding 5 to the list
    item.setValue(5);
    myList.PutItem(item);

    // Adding 8 to the list
    item.setValue(8);
    myList.PutItem(item);

    // Printing the list
    myList.Print();

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

I have changed the Dlists.cpp implementation for FindItem() and PutItem() Functions,

FindItem function always returns the pointer next to which we need to put the new Item. If it returns nullptr, then our new node must be inserted to the head position else we Insert the new node to the next of location pointer. Corresponding changes to the code have been made. Good Luck!

#ifndef ITEMTYPE_H
#define ITEMTYPE_H

enum RelationType { LESS, GREATER, EQUAL};

class ItemType
{
public:
ItemType();
void setValue(int newValue);
int getValue() const;
RelationType ComparedTo(ItemType newItem);

private:
int value;
};

#endif // ITEMTYPE_H


// ItemType.cpp

#include "ItemType.h"

ItemType::ItemType()
{
value = 0;
}

void ItemType::setValue(int newValue)
{
value = newValue;
}

int ItemType::getValue() const
{
return value;
}

RelationType ItemType::ComparedTo(ItemType newItem)
{
if (value < newItem.value)
return LESS;
else if (value > newItem.value)
return GREATER;
else
return EQUAL;
}


// Dlists.h

#ifndef DLISTS_H
#define DLISTS_H

#include "ItemType.h"

struct NodeType;

class Dlists
{
public:
Dlists();
void FindItem(NodeType *head, ItemType item, NodeType *& location, bool &found);
void PutItem(ItemType item);
void DeleteItem(ItemType item);
void Print() const;

private:
NodeType *head;
int length;
NodeType *currentPos;
};

#endif // DLISTS_H

#include "Dlists.h"
#include <iostream>
using namespace std;

struct NodeType
{
NodeType *next;
NodeType *prev;
ItemType info;
};

Dlists::Dlists()
{
head = nullptr;
currentPos = nullptr;
length = 0;
}

void Dlists::Print() const
{
NodeType *temp = head;
while (temp != nullptr)
{
cout << temp->info.getValue() << " ";
temp = temp->next;
}
}
//FindItem returns the pointer next to which we need to insert the other node
void Dlists::FindItem(NodeType *head, ItemType item, NodeType *&location, bool &found)
{
location = head;
NodeType* prev=nullptr;
found = false;

while (location!=nullptr && !found)
{
if(item.ComparedTo(location->info) == EQUAL)
found = true;
else if (item.ComparedTo(location->info) == LESS)
{
location=prev;
found=true;
}
else // greater
{
prev=location;
location = location->next;
}
}
if(location==nullptr) location=prev;
}

void Dlists::PutItem(ItemType item)
{
NodeType *location;
bool found;

// create a new node with the item data
NodeType *newNode;
newNode = new NodeType;
newNode->info = item;

if (length == 0) // if list is empty
{
head = newNode;
newNode->next = nullptr;
newNode->prev = nullptr;
}
else if (length == 1)
{
if(item.ComparedTo(head->info) == LESS)
{
newNode->prev = nullptr;
newNode->next = head;
head->prev = newNode;
head = newNode;
}
else // if item is greater than the sole node
{
newNode->prev = head;
newNode->next = nullptr;
head->next = newNode;
}
}
else // insertion point is next to the location pointer
{
FindItem(head, item, location, found);
//FindItem always returns a pointer after which we need to insert the next node
if(location==nullptr){
newNode->next=head;
head->prev=newNode;
head=newNode;
}
else{
newNode->prev=location;
newNode->next=location->next;
location->next=newNode;
//cout<<location->info.getValue()<<endl;
}
}

// increment the list
length++;
}

// driver.cpp

#include "Dlists.h"
#include <iostream>
using namespace std;

int main()
{
Dlists myList;
ItemType item;

// Adding 2 to the list
item.setValue(2);
myList.PutItem(item);

// Adding 5 to the list
item.setValue(5);
myList.PutItem(item);

// Adding 8 to the list
item.setValue(8);
myList.PutItem(item);

// Printing the list
myList.Print();

}

Add a comment
Know the answer?
Add Answer to:
Double linked list implementation of PutItem function. How to fix my code to get desired output b...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I have a problem with merging the two linked lists together. In the function AscendMerge, I...

    I have a problem with merging the two linked lists together. In the function AscendMerge, I am trying to compare the values of each node in the two lists and output them into one list in ascended order. Everything works except for the one function. Can someone tell me what im doing wrong, when I run it it skips over values. #include <iostream> #include <cassert> using namespace std; struct nodeType {    int info;    nodeType *link;    nodeType *current;...

  • Fill in the missing code in the following code segment to insert node into list.   ...

    Fill in the missing code in the following code segment to insert node into list.    void SortedType::PutItem(ItemType newItem) {                            NodePtr* newNode;                        // pointer to node being inserted                            NodePtr* predLoc;              // trailing pointer                            NodePtr* location;               // traveling pointer                            boolean moreToSearch;                            location = listData;                            predLoc = NULL;                            moreToSearch = (location != NULL);                            length++;                            // Find insertion point while (moreToSearch)                            { if (location->info < newItem) { predLoc = location; location = location->next; moreToSearch = (location != NULL); }                                        else                                                         moreToSearch = false;                            }                            // Prepare...

  • Design and implement your own linked list class to hold a sorted list of integers in ascending order. The class should h...

    Design and implement your own linked list class to hold a sorted list of integers in ascending order. The class should have member function 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 member functions to display the list, check if...

  • Class SortedList { Public: SortedType(); int getLength(); //returns size of the list void putItem(Itemtype item); //inserts...

    Class SortedList { Public: SortedType(); int getLength(); //returns size of the list void putItem(Itemtype item); //inserts an item Itemtype getNextItem(); //returns the next item pointed by the index void deleteItem(Itemtype item) //deletes a specified item Private: int length; //length of the list Nodetype* listData //head of the list Nodetype* currentPos; //current pointer to the list } Class Itemtype { Public: Itemtype(); int getValue();// returns the value Private: int value; } struct Nodetype { Itemtype info; Nodetype* next; } Add a...

  • Write a function, swapSubtrees, that swaps all of the left and right subtrees of a binary...

    Write a function, swapSubtrees, that swaps all of the left and right subtrees of a binary tree. Add this function to the class binaryTreeType and create a program to test this function. #include <iostream> using namespace std; //Definition of the Node template <class elemType> struct nodeType { elemType info; nodeType<elemType> *lLink; nodeType<elemType> *rLink; }; //Definition of the class template <class elemType> class binaryTreeType { public: //Overload the assignment operator. const binaryTreeType<elemType>& operator=(const binaryTreeType<elemType>&) { if (this != &otherTree) //avoid self-copy...

  • Hello, this is my code and it have redefinition error, please help me to fix it...

    Hello, this is my code and it have redefinition error, please help me to fix it //doublenode.hpp #ifndef DOUBLENODE_HPP #define DOUBLENODE_HPP template<class ItemType> class DoubleNode { private: ItemType item; DoubleNode<ItemType>* next; DoubleNode<ItemType>* prev; public: DoubleNode(); DoubleNode(const ItemType& anItem); DoubleNode(const ItemType& anItem,DoubleNode<ItemType>* nextNodePtr, DoubleNode<ItemType>* previousNodePtr); void setItem(const ItemType& anItem); ItemType getItem() const; void setNext(DoubleNode<ItemType>* nextNodePtr); DoubleNode<ItemType>* getNext() const; void setprevious(DoubleNode<ItemType>* previousNodePtr); DoubleNode<ItemType>* getPrevious() const; }; #include "DoubleNode.cpp" #endif //doblenode.cpp //#ifndef DOUBLE_NODE_CPP //#define DOUBLE_NODE_CPP #include "DoubleNode.hpp" template <class ItemType> DoubleNode<ItemType>::DoubleNode():next(nullptr),prev(nullptr) { }...

  • The program I wrote has a few memory leaks. My assignment is to just fix the...

    The program I wrote has a few memory leaks. My assignment is to just fix the memory leaks. Here's the code: bool RemoveTail() { if (tail == nullptr) return false; Node *ptr = tail; if(tail->prev != nullptr) { tail = tail->prev; tail->next = nullptr; } else { tail = nullptr; head = nullptr; } delete ptr; ptr = nullptr; length--; return true; } bool RemoveAt(const unsigned int index) { if(index >= length || index < 0) return false; unsigned int...

  • Introduction In this lab, you are supposed to implement a graph class with the data structure...

    Introduction In this lab, you are supposed to implement a graph class with the data structure implemented before like linked list and queue. graph The class graph contains three member variables: linkedList *adjacentVertices; //an array of linked list. For a vertice i, adjacentVertices[i] stores the linked list that contains all other vertices connected to vertice i. int numVertices; //The number of vertices in the graph. int maxNumVertices; //The maximum number of vertices the graph can hold. Following public methods are...

  • Using the provided table interface table.h and the sample linked list code linkedList.c, complete an implementation...

    Using the provided table interface table.h and the sample linked list code linkedList.c, complete an implementation of the Table ADT. Make sure that you apply the concepts of design by contract (DbC) to your implementation. Once you have fully implemented the table, create a main.c file that implements a testing framework for your table. Your table implementation must ensure that values inserted are unique, and internally sorted within a linked list. table.h #ifndef _TABLE_H #define _TABLE_H //----------------------------------------------------------------------------- // CONSTANTS AND...

  • (The SortedLinkedList class template) Complete the SortedLinkedList class template which is a doubly linked list and...

    (The SortedLinkedList class template) Complete the SortedLinkedList class template which is a doubly linked list and is implemented with a header node and a tail node. // SortedLinkedList.h // SortedLinkedList.h // A collection of data are stored in the list by ascending order #ifndef SORTEDLIST_H #define SORTEDLIST_H using namespace std; template <typename T> class SortedList { private: // The basic single linked list node type. // Nested inside of SortedList. struct NodeType { T data; NodeType* next; NodeType* prev; NodeType(const...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT