Question

In: Computer Science

Add the following methods to the singly list implementation below. int size(); // Returns the number...

Add the following methods to the singly list implementation below.

int size(); // Returns the number of nodes in the linked list
bool search(string query); // Returns if the query is present in the list
void add(List& l); // // Adds elements of input list to front of "this" list (the list that calls the add method)

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

// slist.cpp

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

using namespace std;

Node::Node(string element) : data{element}, next{nullptr} {}

List::List() : first{nullptr} {}

// Adds to the front of the list
void List::pushFront(string element) {
Node* new_node = new Node(element);
if (first == nullptr) {// List is empty
first = new_node;
} else {
new_node->next = first;
first = new_node;
}
}

Iterator List::begin() {
Iterator iter;
iter.position = first;
iter.container = this;
return iter;
}

Iterator List::end() {
Iterator iter;
iter.position = nullptr;
iter.container = this;
return iter;
}

// Returns number of elements in the list
int List::size() {
// Q1: Your code here


}

// Returns if query is present in list (true/false)
bool List::search(string query) {
// Q2: Your code here


}

// Adds elements of input list to front of "this" list
void List::add(List& l) {
// Q3. Your code here

}

Iterator::Iterator() {
position = nullptr;
container = nullptr;
}

string Iterator::get() const {
return position->data;
}

void Iterator::next() {
position = position->next;
}

bool Iterator::equals(Iterator other) const {
return position == other.position;
}

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Use the following header file, and test program (not to be modified or uploaded!) to verify that your methods works correctly. The expected output is indicated slist.cpp

Note:

1. Please make sure to implement one method at a time (compile, and test). Comment out the unimplemented methods as you work along.

2. Please be sure to check that the code uploaded is indeed the one you intended to upload.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

// slist.h file

/* Singly linked list */
#ifndef LIST_H
#define LIST_H

#include <string>

using namespace std;

class List;
class Iterator;

class Node
{
public:
Node(string element);
private:
string data;
Node* previous;
Node* next;
friend class List;
friend class Iterator;
};

class List
{
public:
List();
void pushFront(string element);
Iterator begin();
Iterator end();
int size();
bool search(string query);
void add(List& l);
private:
Node* first;
friend class Iterator;
};

class Iterator
{
public:

Iterator();
string get() const;
void next();
bool equals(Iterator other) const;
private:
Node* position;
List* container;
friend class List;
};

#endif

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

// slist_test.cpp

#include <string>
#include <iostream>
#include "slist.h"

using namespace std;

int main()
{
List names1;

names1.pushFront("Alice");
names1.pushFront("Bob");
names1.pushFront("Carol");
names1.pushFront("David");

// names1 is now - David Carol Bob Alice

int numele = names1.size(); // Q1: TO BE COMPLETED
cout << "Number of elements in the list: " << numele << endl;

string query = "Eve";
bool present = names1.search(query); // Q2: TO BE COMPLETED
if (present) {
cout << query << " is present" << endl;
} else {
cout << query << " is absent" << endl;
}


List names2;
names2.pushFront("Eve");
names2.pushFront("Fred");

// names2 is now - Fred Eve

// Insert each element of input list (names1) to front of calling list (names2)
names2.add(names1); // Q3: TO BE COMPLETED

// Print extended list
// Should print - Alice Bob Carol David Fred Eve
for (Iterator pos = names2.begin(); !pos.equals(names2.end()); pos.next()) {
cout << pos.get() << " ";
}
cout << endl;
return 0;
}

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Thank you for your time and help

Solutions

Expert Solution

#######################################
            main.cpp
#######################################
#include <string>

#include <iostream>

#include "slist.h"

using namespace std;

int main()

{

List names1;

names1.pushFront("Alice");

names1.pushFront("Bob");

names1.pushFront("Carol");

names1.pushFront("David");

// names1 is now - David Carol Bob Alice

int numele = names1.size(); // Q1: TO BE COMPLETED

cout << "Number of elements in the list: " << numele << endl;

string query = "Eve";

bool present = names1.search(query); // Q2: TO BE COMPLETED

if (present) {

cout << query << " is present" << endl;

} else {

cout << query << " is absent" << endl;

}

List names2;

names2.pushFront("Eve");

names2.pushFront("Fred");

// names2 is now - Fred Eve

// Insert each element of input list (names1) to front of calling list (names2)

names2.add(names1); // Q3: TO BE COMPLETED

// Print extended list

// Should print - Alice Bob Carol David Fred Eve

for (Iterator pos = names2.begin(); !pos.equals(names2.end()); pos.next()) {

cout << pos.get() << " ";

}

cout << endl;

return 0;

}



#######################################
           slist.cpp
#######################################
#include <string>

#include "slist.h"

using namespace std;

Node::Node(string element) : data(element), next(nullptr) {}

List::List() : first(nullptr) {}

// Adds to the front of the list

void List::pushFront(string element) {

Node* new_node = new Node(element);

if (first == nullptr) {// List is empty

first = new_node;

} else {

new_node->next = first;

first = new_node;

}

}

Iterator List::begin() {

Iterator iter;

iter.position = first;

iter.container = this;

return iter;

}

Iterator List::end() {

Iterator iter;

iter.position = nullptr;

iter.container = this;

return iter;

}

// Returns number of elements in the list

int List::size() {
        int count = 0;
        Node *start = first;
        while(start != nullptr) {
                count++;
                start = start->next;
        }
        return count;
}

// Returns if query is present in list (true/false)
bool List::search(string query) {
        Node *start = first;
        while(start != nullptr) {
                if(start->data == query) {
                        return true;
                }
                start = start->next;
        }
        return false;
}

// Adds elements of input list to front of "this" list
void List::add(List& l) {
        Node *start = l.first;
        while(start != nullptr) {
                pushFront(start->data);
                start = start->next;
        }
}

Iterator::Iterator() {

position = nullptr;

container = nullptr;

}

string Iterator::get() const {

return position->data;

}

void Iterator::next() {

position = position->next;

}

bool Iterator::equals(Iterator other) const {

return position == other.position;

}



#######################################
             slist.h
#######################################
/* Singly linked list */
#ifndef LIST_H
#define LIST_H

#include <string>

using namespace std;

class List;
class Iterator;

class Node {

public:

Node(string element);

private:

string data;

Node* previous;

Node* next;

friend class List;

friend class Iterator;

};

class List

{

public:

List();

void pushFront(string element);

Iterator begin();

Iterator end();

int size();

bool search(string query);

void add(List& l);

private:

Node* first;

friend class Iterator;

};

class Iterator

{

public:

Iterator();

string get() const;

void next();

bool equals(Iterator other) const;

private:

Node* position;

List* container;

friend class List;

};

#endif


**************************************************

Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.

Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.


Related Solutions

Add the following methods to the singly list implementation below. int size(); // Returns the number...
Add the following methods to the singly list implementation below. int size(); // Returns the number of nodes in the linked list bool search(string query); // Returns if the query is present in the list void add(List& l); // // Adds elements of input list to front of "this" list (the list that calls the add method) #include <string> #include "slist.h" using namespace std; Node::Node(string element) : data{element}, next{nullptr} {} List::List() : first{nullptr} {} // Adds to the front of...
Q1) In the implementation of Singly linked list we had an integer variable called size that...
Q1) In the implementation of Singly linked list we had an integer variable called size that keeps track of how many elements in the list. Also, we have a reference “tail” that points to the last node in the list. You are asked to re-implement the concept of singly linked list without using variable size, and without using reference “tail”. a) What are the methods of the main operation of singly linked list that need to be changed? Rewrite them...
Python Add your own implementation of the function rearrange_list rearrange_list(linkedlist, number) returns the result of rearranging...
Python Add your own implementation of the function rearrange_list rearrange_list(linkedlist, number) returns the result of rearranging the nodes in linkedlist so that: all the nodes whose values are less than number are at the front all the nodes whose values are greater than number are at the rear any nodes whose values are equal to number are in the middle For example, given the linked list represented by linkedlist = -2 -> -3 -> -1 -> 2 -> 3 ->...
You are provided with a partial implementation of a templated singly-linked list in LinkedList.h, with some...
You are provided with a partial implementation of a templated singly-linked list in LinkedList.h, with some missing functionality. It contains a templated Node class and a templated LinkedList class. Do not modify the class definitions. The linked list class contains the following methods: • LinkedList – Constructor of a linked list with a head pointing to null (implemented). • ~LinkedList – Destructor of a linked list. • deleteFromHead – Removes and returns content of the first node of the list....
def largest_rectangle_in_matrix(matrix: List[List[int]]) -> int: """ Returns the area of the largest rectangle in <matrix>. The...
def largest_rectangle_in_matrix(matrix: List[List[int]]) -> int: """ Returns the area of the largest rectangle in <matrix>. The area of a rectangle is defined as the number of 1's that it contains. Again, you MUST make use of <largest_rectangle_at_position> here. If you managed to code largest_rectangle_at_position correctly, this function should be very easy to implement. Similarly, do not modify the input matrix. Precondition: <matrix> will only contain the integers 1 and 0. >>> case1 = [[1, 0, 1, 0, 0], ... [1,...
Add a copy constructor for the linked list implementation below. Upload list.cpp with your code added....
Add a copy constructor for the linked list implementation below. Upload list.cpp with your code added. (DO NOT MODIFY THE HEADER FILE OR TEST FILE. only modify the list.cpp) /*LIST.CPP : */ #include "list.h" using namespace std; // Node class implemenation template <typename T> Node<T>::Node(T element) { // Constructor    data = element;    previous = nullptr;    next = nullptr; } // List implementation template <typename T> List<T>::List() {    head = nullptr;    tail = nullptr; } template...
// Given an int array of size elements, determine if there are k elements that add...
// Given an int array of size elements, determine if there are k elements that add up to sum. // The array holds integers, both positive and negative and zero. // It is not possible to add zero elements (that's when k==0) to any sum, not even zero. // It is not possible to add any elements from an empty array. // Must be recursive and not iterative //bool K_element_sum(size_t k, int sum, int arr[], size_t size){}
Write function boolean isSorted(int a[], int size). The function returns true if array a is sorted...
Write function boolean isSorted(int a[], int size). The function returns true if array a is sorted in either ascend order or descend order; false otherwise. c++
class SLinkedList: """Singly linked list with access to front and end, and with stored size. """...
class SLinkedList: """Singly linked list with access to front and end, and with stored size. """ #-------------------------- nested _Node class -------------------------- class _Node: __slots__ = '_element', '_next' # streamline memory usage def __init__(self, element, next): self._element = element self._next = next #------------------------------- queue methods ------------------------------- def __init__(self): """Create an empty list.""" self._head = None self._tail = None self._size = 0 def __len__(self): """Return the number of elements in the list.""" return self._size def isEmpty(self): """Return True if the list is...
1. Adapt the custom array list implementation code with the following changes: (a) Add code to...
1. Adapt the custom array list implementation code with the following changes: (a) Add code to the ensureCapacity() method to print out a message including how many elements are copied to the new array on resizing Array List Implementation: public class MyArrayList<E> implements MyList<E> { public static final int INITIAL_CAPACITY = 16; private E[] data = (E[])new Object[INITIAL_CAPACITY]; private int size = 0; // Number of elements in the list public MyArrayList() { }    public MyArrayList(E[] objects) { for...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT