Question

In: Computer Science

Flow this Code to answer question below #include <iostream> using std::cout; struct Node {     int...

Flow this Code to answer question below

#include <iostream>

using std::cout;

struct Node {

    int data;

    Node *link;

                 Node(int data=0, Node *p = nullptr) { //Note, this constructor combines both default and parameterized constructors. You may modify the contructor to your needs

        this->data = data;

                                  link = p;

    }

};

class linked_list

{

private:

    Node *head,*current;

public:

     //constructor

    linked_list() {

        head = nullptr;//the head pointer

        current = nullptr;//acts as the tail of the list

    }

    //destructor - IMPORTANT

    ~linked_list() {

                                  current = head;

                                  while( current != nullptr ) {//the loop stops when both current and head are NULL

                                  head = head->link;

                                  delete current;

                                  current = head;

                                  }

    }

    void addLast(int n) {// to add a node at the end of the list

        if(head == nullptr){

            head = new Node(n);

            current = head;

        } else {

                                                   if( current->link != nullptr)

                                                                    current = current->link;

            current->link = new Node(n);

            current = current->link;//You may decide whether to keep this line or not for the function

        }

    }

   

    void print() { // to display all nodes in the list

        Node *tmp = head;

        while (tmp != nullptr) {

            cout << tmp->data << std::endl;

            tmp = tmp->link;

        }

    }

};

int main() {

    linked_list a;

    a.addLast(1);

   a.addLast(2);

                 a.print();

   

    return 0;

}

Question:

Create the node structure and the linked list class. The sample class has implemented the following member methods:

o constructor

o destructor

o print(),

o addLast()

2. Implement the following member methods:

▪ addFirst (T data) // Adds a node with data at the beginning of the list

▪ pop() // Removes the first node of the list. Note: Don't forget to delete/reallocate the removed dynamic memory

▪ contains(T data) // Returns true or false if a node contains the data exists in the list

▪ update(T oldDate, T newData) // Updates the oldData of a node in the list with newData.

▪ size() // Returns the number of nodes in the list

▪ remove( T data) //Removes the node that contains the data. Note, you will need to check if the node exists. Again, don't forget to delete/re-allocate the dynamic memory

3. (Extra Credit Part) Implement the following additional member methods

▪ insertAfter(int n, T data) //Adds a node after the n-th node. Note, you will need to check if the n th node exists, if not, do addLast().

▪ merge(const LinkedList &linkedlist) //Merges this object with linkedlist object. In other words, add all nodes in linkedlist to this object.

Solutions

Expert Solution

#include <iostream>
#include <cstddef>
using std::cout;


template <typename T>
struct Node {
T data;
Node *link;
  
   Node(T data)
   {
        this->data = data;
       link = NULL;
   }
   Node(T data, Node *p ) { //Note, this constructor combines both default and parameterized constructors. You may modify the contructor to your needs
this->data = data;
       link = p;
}
};

template <typename T>
class linked_list
{
Node<T> *head,*current;
public:
//default constructor
linked_list() {
head = NULL;//the head pointer
current = NULL;//acts as the tail of the list
}

//destructor - IMPORTANT
~linked_list() {
       current = head;
       while( current != NULL ) {//the loop stops when both current and head are NULL
       head = head->link;
       delete current;
       current = head;
       }
}

void addLast(int n) {// to add a node at the end of the list
if(head == NULL){
head = new Node<T>(n);
current = head;
} else {
           if( current->link != NULL)
               current = current->link;
current->link = new Node<T>(n);
current = current->link;//You may decide whether to keep this line or not for the function
}
}
  
void print() { // to display all nodes in the list
Node<T> *tmp = head;
while (tmp != NULL) {
cout << tmp->data << "\n";
tmp = tmp->link;
}
}

// addFirst Method
void addFirst(T data)
{
        Node<T> *temp=new Node<T>(data);
        temp->link=head;
        head=temp;
        if(current==NULL)
           current=head;
}

// pop 
T pop()
{
        if(head==NULL)
           return NULL;
        Node<T> *temp=head;
        head=head->link;
        if(head==NULL) // if there is now node remaining
          current=NULL;
    T data=temp->data;
    delete temp;
    return data;
}

// contains()
bool contains(T data)
{
        Node<T> *temp=head;
        while(temp!=NULL)
        {
                if(temp->data==data)
                   return true;
                temp=temp->link;
        }
        return false;
}

// update()
void update(T oldData,T newData){
        Node<T> *temp=head;
        while(temp!=NULL)
        {
                if(temp->data==oldData)
                {
                        temp->data=newData;
                        break;
                }
                temp=temp->next;
        }
}

// size()

int size()
{
        Node<T> *temp=head;
        int count=0;
        while(temp!=NULL)
        {
                count++;
                temp=temp->link;
        }
        return count;
}

// remove method

void remove(T data)
{
        if(contains(data))
        {
                Node<T> *temp=head,*pre=NULL;
                while(temp!=NULL)
                {
                        if(temp->data==data)
                           break;
                        pre=temp;
                        temp=temp->link;
                }
                if(pre==NULL) // remove head
                   pop();
                else
                {
                        pre->link=temp->link;
                        delete temp;
                }
        }
}

//insert after n
void insertAfter(int n,T data)
{
        Node<T> *node=new Node<T>(data);
        if(size()<=n)
           addLast(data);
        else
        {
                Node<T> *temp=head,*pre;
                while(n>0)
                {
                        n--;
                        pre=temp;
                        temp=temp->link;
                }
                pre->link=node;
                node->link=temp;
        }
}
void merge(const linked_list &linkedlist)
{
        // first list is empty
        if(head==NULL)
           head=linkedlist.head;
        else
        {
                Node<T> *temp=head;
                while(temp->link!=NULL)
                   temp=temp->link;
                temp->link=linkedlist.head;
        }
}

};

int main() {
linked_list<int> a;
a.addLast(1);
a.addLast(2);
cout<<"\nList is :  \n";
  a.print();
a.addFirst(3);
cout<<"\nList after addFirst() is : \n ";
  a.print();
  a.pop();
cout<<"\nList after pop() is :  \n";
  a.print();
cout<<"\nSize of List is :  "<<a.size();
a.insertAfter(2,5);
cout<<"\nList after insertAfter() is :  \n";
  a.print();
a.remove(5);
cout<<"\nList after remove(5) is :  \n";
  a.print();
cout<<"\nIs List contains(5) :  "<<a.contains(5);
 linked_list<int> b;
b.addLast(10);
b.addLast(20);
cout<<"List b is:\n";
b.print();
a.merge(b);
cout<<"list after merging a and b is :\n";
a.print();
return 0;
}

I tested and the output is

List is :                                                                                                  

1                                                                                                          

2                                                                                                          

                                                                                                           

List after addFirst() is :                                                                                 

3                                                                                                         

1                                                                                                          

2                                                                                                          

                                                                                                           

List after pop() is :                                                                                      

1                                                                                                          

2                                                                                                          

                                                                                                           

Size of List is :  2                                                                                       

List after insertAfter() is :                                                                              

1                                                                                                          

2                                                                                                          

5                                                                                                          

                                                                                                           

List after remove(5) is :                                                                                  

1                                                                                                          

2   

5                                                                                                          

                                                                                                           

List after remove(5) is :                                                                                  

1                                                                                                          

2                                                                                                          

                                                                                                           

Is List contains(5) :  0List b is:                                                                         

10                                                                                                         

20                                                                                                         

list after merging a and b is :                                                                            

1                                                                                                          

2                                                                                                          

10                                                                                                         

20

Hope this is helpful

Please please upvote if helpful and please dont downvote please


Related Solutions

Given: #include <iostream> using std::cout; template <typename T> struct Node { T data; Node *link;   ...
Given: #include <iostream> using std::cout; template <typename T> struct Node { T data; Node *link;       Node(T data=0, Node *p = nullptr) { //Note, this constructor combines both default and parameterized constructors. You may modify the contructor to your needs this->data = data;        link = p; } }; template <typename T> class linked_list { Node<T> *head,*current; public: //default constructor linked_list() { head = nullptr;//the head pointer current = nullptr;//acts as the tail of the list } //destructor...
***Convert the C++ to Python*** #include <iostream> using std::cout; using std::cin; using std::endl; int charClass; char...
***Convert the C++ to Python*** #include <iostream> using std::cout; using std::cin; using std::endl; int charClass; char lexeme[100]; char str[200]; char nextChar; const int LETTER = 0; const int DIGIT   = 1; const int UNKNOWN = -1; const int OPAREN = 2; const int CPAREN = 3; const int PLUS = 4; const int MINUS = 5; const int MUL = 6; const int DIV = 7; const int ID_CODE = 100; const int PLUS_CODE = 101; const int MINUS_CODE =...
#include "IntVariableTable.h" #include "Tokens.h" #include <assert.h> #include <iostream> #include <iomanip> using std::cout; using std::endl; using std::left;...
#include "IntVariableTable.h" #include "Tokens.h" #include <assert.h> #include <iostream> #include <iomanip> using std::cout; using std::endl; using std::left; using std::right; using std::setw; using std::string; // The IntVariableTable constructor dynamically allocates the fixed size array of integer variables. IntVariableTable::IntVariableTable() { int_variable_table = new IntVariableEntry[MAX_INT_VARIABLES]; } // The IntVariableTable destructor deallocates the integer variable array. IntVariableTable::~IntVariableTable() { delete[] int_variable_table; } // Returns the number of variables added to the integer variable table. int IntVariableTable::numVariables() const { return num_int_variables; } // Returns the index of...
Complete the C++ code #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; struct Cell {...
Complete the C++ code #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; struct Cell { int val; Cell *next; }; int main() { int MAX = 10; Cell *c = NULL; Cell *HEAD = NULL; srand (time(NULL)); for (int i=0; i<MAX; i++) { // Use dynamic memory allocation to create a new Cell then initialize the // cell value (val) to rand(). Set the next pointer to the HEAD and // then update HEAD. } print_cells(HEAD); }
Question 1 Given the program below, what are the errors. #include <iostream> using namespace std; int...
Question 1 Given the program below, what are the errors. #include <iostream> using namespace std; int main() { int ind_square(int &); int x, *p; x=15; p = &x; ind_square(*p); } int ind_square(int &p) { *p = *p **p; } Question 1 options: C. No return for non-void function A. Indirection for the variables in ind_square requires pointer operand A and B B. Invalided use of address (&) symbol as a parameter for ind_squared A and C Question 2 Which statement...
write the algorithm for this the code?!. #include<iostream> using namespace std; #include<string.h> int main() { char...
write the algorithm for this the code?!. #include<iostream> using namespace std; #include<string.h> int main() { char plain[50], cipher[50]="", decrypt[50]=""; int subkeys[50], len;       cout<<"Enter the plain text:"<<endl; cin>>plain;    cout<<"Enter the first subkey:"<<endl; cin>>subkeys[0];    _strupr(plain);    len = strlen(plain);    /**********Find the subkeys**************/    for(int i=1; i<len; i++) { if ((plain[i-1]>='A') && (plain[i-1]<='Z')) { subkeys[i] = plain[i-1]-65; } }    /****************ENCRYPTION***************/       for(int i=0; i<len; i++) { if ((plain[i]>='A') && (plain[i]<='Z')) {    cipher[i] = (((plain[i]-65)+subkeys[i])%26)+65; }...
#include <iostream> #include <fstream> #include <vector> using namespace std; struct Point{ int x, y; bool operator==(const...
#include <iostream> #include <fstream> #include <vector> using namespace std; struct Point{ int x, y; bool operator==(const Point& p2) { return this->x == p2.x and this->y == p2.y; } bool operator!=(const Point& p2) { return this->x != p2.x or this->y != p2.y; } friend ostream &operator<<( ostream &out, const Point &P ) { out << "(" << P.x << ", " << P.y << ")"; return out; } friend istream &operator>>( istream &in, Point &P ) { char d1, d2, d3;...
Please debug the code and answer the questions: #include <stdio.h> typedef struct node { int value;...
Please debug the code and answer the questions: #include <stdio.h> typedef struct node { int value; struct node *next; } node; int ll_has_cycle(node *first) { node * head = first; while (head->next) { head = head->next; if (head == first) return 1; } return 0; } void test_ll_has_cycle(void) { int i,j; node nodes[5]; for(i=0; i < sizeof(nodes)/sizeof(node); i++) { nodes[i].next = NULL; nodes[i].value = i; } nodes[0].next = &nodes[1]; nodes[1].next = &nodes[2]; nodes[2].next = &nodes[1]; printf("Checking first list for cycles....
#include <cstring> #include <stdio.h> #include <iostream> using namespace std; int main() {        const int...
#include <cstring> #include <stdio.h> #include <iostream> using namespace std; int main() {        const int SIZE = 20;     char str[SIZE];     char str1[SIZE];     int n;     int k =1;        printf("Enter a word: \n");     fgets(str,SIZE,stdin);     printf("Enter another word: \n");     fgets(str1,SIZE,stdin);        if (str1[strlen(str1) - 1] == '\n')     {         str1[strlen(str1)-1] = '\0';     }     if (str[strlen(str) - 1] == '\n')     {         str[strlen(str)-1] = '\0';     }      ...
C++ Given Code: #include <iostream> #include <string> using namespace std; int main() { //declare variables to...
C++ Given Code: #include <iostream> #include <string> using namespace std; int main() { //declare variables to store user input bool cont = true; //implement a loop so that it will continue asking until the user provides a positive integer // the following provides ONLY part of the loop body, which you should complete { cout <<"How many words are in your message? \n"; cout <<"Enter value: "; // get user input integer here    cout <<"\nInvalid value. Please Re-enter a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT