Question

I need help with understanding dummy nodes in doubly-linked lists. Here is the code that I...

I need help with understanding dummy nodes in doubly-linked lists.

Here is the code that I have right now.

************city.h****************

#ifndef city_h

#define city_h

#include <string>

using namespace std;

class City{

public:

City () {

name = "N/A";

population = 0;

}

City (string nm, unsigned int pop){

name = nm;

population = pop;

}

void setName (string name) {

this -> name = name;

}

void setPopulation (unsigned int population){

this -> population = population;

}

string getName() const {

return this -> name;

}

unsigned int getPopulation() const {

return this -> population;

}

virtual void printInfo() const {

cout << getName() << ": " << getPopulation() << endl;

}

protected:

string name;

unsigned int population;

};

#endif /* city_h */

************citynode.h***************

#ifndef citynode_h

#define citynode_h

#include <string>

#include "city.h"

class CityNode {

public:

City data;

CityNode *next;

CityNode *prev;

CityNode (City city){

data = city;

next = nullptr;

}

};

#endif /* citynode_h */

********************citylist.h********************

#ifndef citylist_h

#define citylist_h

#include<string>

#include<list>

#include "citynode.h"

using namespace std;

class CityList{

public:

CityList(){

head = tail = nullptr;

}

void append(CityNode *cityNode){

if(tail == nullptr){

head = tail = cityNode;

return;

}

tail -> next = cityNode;

cityNode -> prev = tail;

tail = tail -> next;

}

void prepend(CityNode *cityNode){

if(head == nullptr){

head = tail = cityNode;

return;

}

cityNode -> next = head;

head -> prev = cityNode;

head = cityNode;

}

void printCityList(){

CityNode *temp = head;

while(temp != nullptr){

cout << temp->data.getName() << " " << temp -> data.getPopulation() << endl;

temp = temp -> next;

}

}

CityNode *search(string cityName){

CityNode *temp = head;

while (temp != nullptr){

if(temp -> data.getName() == cityName){

return temp;

temp = temp -> next;

}

}

return nullptr;

}

void insert(CityNode *currNode, CityNode *cityNode) {

   if(currNode == nullptr) {

   head = tail = cityNode;

   return;

   }

   else if(currNode->next == tail) {

   tail->next = cityNode;

   cityNode->prev = tail;

   tail = cityNode;

   return;

   }

   else {

   cityNode->next = currNode->next;

   cityNode->next = cityNode->prev;

   cityNode->prev = currNode;

   currNode->next = cityNode;

   cityNode->prev = cityNode;

   }

   }

       void remove(CityNode *currNode) {

   if(currNode == nullptr || currNode->next == nullptr) {

   if(currNode == head) {

   free(head);

   head = nullptr;

   }

   return;

   }

   CityNode *temp = currNode->next;

   currNode->next = currNode->next->next;

   free(temp);

   }

  

private:

CityNode *head;

CityNode *tail;

};

#endif /* citylist_h */

*****************main.cpp*********************

#include <iostream>

#include "citylist.h"

using namespace std;

City cityArray[] = {{"Los Angeles", 4340174}, {"San Diego", 1591688},{"San Francisco", 871421}, {"Sacramento", 505628}, {"Stockton", 323761}, {"Redding", 90292}, {"Las Vegas", 711926}, {"Reno", 289485}, {"Portland", 730428}, {"Seattle", 752180}, {"Eugene", 221452}};

CityList cityList1, cityList2;

void initCityListByAppend(CityList &city1, City arr[], int size){

for(int i = 0; i < size; i++){

CityNode *cityNode = new CityNode(arr[i]);

city1.append(cityNode);

}

}

void initCityListByPrepend(CityList &city2, City arr[], int size){

for(int i = 0; i < size; i++){

CityNode *cityNode = new CityNode(arr[i]);

city2.prepend(cityNode);

}

}

int main() {

cout << "Initialize cityList1 according to array cityArray[] by appending: " << endl;

initCityListByAppend(cityList1, cityArray, 11);

cityList1.printCityList();

cout << endl;

cout << "Initializing cityList2 with cityArray[] using prepending: " << endl;

initCityListByPrepend(cityList2, cityArray, 11);

cityList2.printCityList();

cout << endl;

  

cout << "Searching for Stockton in cityList, and inserting Phoenix after it:" << endl;

   CityNode *k = cityList1.search("Stockton");

   if(k == nullptr) {

   cout << "Not found " <<endl;

   }

   else {

   City phoenixCity("Phoenix", 1660472);

   CityNode *cityNode = new CityNode(phoenixCity);

   cityList1.insert(k, cityNode);

   cityList1.printCityList();

   }

   cout << endl;

  

cout << "Searching for Reno in cityList, and removing the node after it:" << endl;

   k = cityList2.search("Reno");

   if(k == nullptr) {

   cout << "Not found " <<endl;

   }

   else {

   cityList2.remove(k);

   cityList2.printCityList();

   }

system("pause");

}

Question:

Consider class CityList that implements the doubly-linked list of cities with dummy node. It keeps track of the first and last elements of the list (through head and tail pointers, respectively).

#ifndef CITYLIST_H

#define CITYLIST_H

#include<string>

#include "citynode.h"

class CityList {

public:

CityList() { head = tail = new CityNode(City());}

void append(CityNode*cityNode);

void prepend(CityNode*cityNode);

void printCityList();

CityNode *search(string cityName);

void insert(CityNode*currNode, CityNode*cityNode);

void remove(CityNode*currNode);

private:

CityNode*head;

CityNode*tail;

};

#endif

Note that the dummy node is created upon constructing the list, and head and tail point to it.

1. Redefine void append(...) function considering the fact that CityList starts with a dummy node. This would make its definition simpler.

2. Redefine void prepend(...) function considering the fact that CityList starts with a dummy node. This would make its definition simpler.

3. Redefine CityNode*search(...) function considering the fact that CityList starts with a dummy node. This would make its definition slightly different.

4. Redefine void printCityList() function considering the fact that CityList starts with a dummy node. This would make its definition slightly different.

5. Redefine void insert(...) function considering the fact that CityList starts with a dummy node. This would make its definition simpler.

6. Redefine void remove(...) function considering the fact that CityList starts with a dummy node. This would make its definition simpler.

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

Given below is the modified code for the question. Please do rate the answer if it helped. Thank you.

citynode.h (fixed this to set prev pointer in constructor)
-----
#ifndef citynode_h
#define citynode_h

#include <string>
#include "city.h"

class CityNode {

public:

City data;

CityNode *next;

CityNode *prev;

CityNode (City city){

data = city;
prev = nullptr;
next = nullptr;

}

};

#endif /* citynode_h */

citylist.h
------
#ifndef citylist_h
#define citylist_h

#include<string>
#include "citynode.h"

using namespace std;

class CityList{

public:

   CityList(){
       head = tail = new CityNode(City()); //dummy node
   }

   void append(CityNode *cityNode){
       tail -> next = cityNode;
       cityNode -> prev = tail;
       tail = tail -> next;
   }

   void prepend(CityNode *cityNode){
       cityNode->next = head->next;
       head->next = cityNode;
       cityNode -> prev = head;
       if(tail == head)
           tail = cityNode;
   }

   void printCityList(){
       CityNode *temp = head->next;
       while(temp != nullptr){
           cout << temp->data.getName() << " " << temp -> data.getPopulation() << endl;
           temp = temp -> next;

       }
   }

   CityNode *search(string cityName){
       CityNode *temp = head->next;
       while (temp != nullptr){
           if(temp -> data.getName() == cityName)
               return temp;
           temp = temp -> next;
       }
       return nullptr;
   }

   void insert(CityNode *currNode, CityNode *cityNode) {
       cityNode->next = currNode->next;
       currNode->next= cityNode;
       cityNode->prev = currNode;
       if(tail == currNode)
           tail = cityNode;
   }
   void remove(CityNode *currNode) {
       if(currNode == nullptr)
           return;
      
       CityNode *nodeToDel = currNode->next;

       if(nodeToDel != nullptr){
           CityNode *next = nodeToDel->next;
           currNode->next = next;
           if(next != nullptr)
               next->prev = currNode;
           else
               tail = currNode;
           delete nodeToDel;
       }
   }


private:

CityNode *head;
CityNode *tail;

};

#endif /* citylist_h */

Add a comment
Know the answer?
Add Answer to:
I need help with understanding dummy nodes in doubly-linked lists. Here is the code that I...
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
  • For the LinkedList class, create a getter and setter for the private member 'name', constructing your...

    For the LinkedList class, create a getter and setter for the private member 'name', constructing your definitions based upon the following declarations respectively: std::string get_name() const; and void set_name(std::string); In the Main.cpp file, let's test your getter and setter for the LinkedLIst private member 'name'. In the main function, add the following lines of code: cout << ll.get_name() << endl; ll.make_test_list(); ll.set_name("My List"); cout << ll.get_name() << endl; Output should be: Test List My List Compile and run your code;...

  • 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)...

  • In this assignment, you will implement a sort method on singly-linked and doubly-linked lists. Implement the...

    In this assignment, you will implement a sort method on singly-linked and doubly-linked lists. Implement the following sort member function on a singly-linked list: void sort(bool(*comp)(const T &, const T &) = defaultCompare); Implement the following sort member function on a doubly-linked list: void sort(bool(*comp)(const T &, const T &) = defaultCompare); The sort(…) methods take as a parameter a comparator function, having a default assignment of defaultCompare, a static function defined as follows: template <typename T> static bool defaultCompare(const...

  • C++ - I have a doubly linked list, but I haven't been able to get the...

    C++ - I have a doubly linked list, but I haven't been able to get the "reverse list" option in the code to work(It's option #in the menu in the program). I received this guidance for testing: Test 4 cases by entering (in this order) c,a,z,k,l,m This tests empty list, head of list, end of list and middle of list. Then delete (in this order) a,z,l. This tests beginning, end and middle deletes. This exhaustively tests for pointer errors. #include...

  • I have a C++ code that lets me enter, display and delete a student record. I...

    I have a C++ code that lets me enter, display and delete a student record. I need to implement a function that prints the average grade score of the students I input. Below is my code and a picture of how my code looks right now. #include<iostream> #include<stdlib.h> using namespace std; //Node Declaration struct node {    string name;    string id;    int score;    node *next;   }; //List class class list {        private:        //head...

  • Main:This is my code for my main, employee.h, and node.h files. I'm trying to rewrite my...

    Main:This is my code for my main, employee.h, and node.h files. I'm trying to rewrite my main to use the node.h to were it is a singly linked list and am failing. Can someone show me how to actually obtain this? #include <iostream> #include <string> #include <stdlib.h> #include <cstdlib> #include <ctime> #include "Employee.h" #include "Node.h" using namespace std; void deleteList(Node** head_ref)  {   Node* current = *head_ref;   Node* next;      while (current != NULL)  {       next = current->next;       free(current);       current = next;   }  ...

  • 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...

  • Im making a generic linked list. I cant figure out how to make an object of...

    Im making a generic linked list. I cant figure out how to make an object of my class from main. My 3 files are main.cpp dan.h dan.cpp The error is: 15 6 [Error] prototype for 'void ll<T>::insert()' does not match any in class 'll<T>' #include <iostream> #include <string> #include "dan.h" using namespace std; int main() { ll<int> work; work.insert(55);//THIS IS THE LINE THATS GIVING ME THE ERROR, Without this line it compiles and //runs. } #ifndef DAN_H #define DAN_H #include...

  • What is the specific answer for 1. and 2. Thanks! Add a new method, find, to...

    What is the specific answer for 1. and 2. Thanks! Add a new method, find, to class SinglyLinkedList (defined here) that takes as input a “data” value and returns a pointer to a node. If the input data is present in the linked list, the returned pointer should point to that node; if not, the returned pointer is nullptr. Write the (single line) method declaration/specification. Write the method definition/implementation. Test by running the main() function below and capture the console...

  • for the following code I need the source code and output screenshot (includes date/time) in a...

    for the following code I need the source code and output screenshot (includes date/time) in a PDF format. I keep getting an error for the #include "dayType.hpp" dayType.cpp #include"dayType.hpp" string dayType::weekday[7] = {"Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat" }; //set the day void dayType::setDay(string day){ cout << "Set day to: " ; cin >> dayType::day; for(int i=0; i<7; i++) { if(dayType::weekday[i]==dayType::day) { dayType::markDay = i; } } } //print the day void dayType::printDay() { cout << "Day = "...

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