Question

In: Computer Science

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 - 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<T>(n);
current = head;
} else {
           if( current->link != nullptr)
               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 != nullptr) {
cout << tmp->data << "\n";
tmp = tmp->link;
}
}
};

int main() {
linked_list<int> a;
a.addLast(1);
a.addLast(2);

   a.print();
  
return 0;
}

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

I managed to find complete solution of your problem. Additionally, I also implemented/called all of these utility functions through our main() method and taken the screenshot of the output. In case you find difficulty in understanding, you can check the comments against that statement.

Lets first look at some key concepts we need to use:-

Add a node at the front:
1) The new node is always added before the head of the given Linked List.
2) And newly added node becomes the new head of the Linked List.
3) For example if the given Linked List is 10->20->30->40 and we add an item 5 at the front, then the Linked List becomes 5->10->20->30->40.

Pop from the beginning:
1) Initialize the head to a temporary node, temp=head.
2) Move the head to next node, head= head -> link.
3) Delete the temporary node, delete temp.

Search for an element:
1) Initialize a node pointer, currentNode = head.
2) Do following while currentNode is not NULL
    a) currentNode->key is equal to the key being searched return true.
    b) currentNode = currentNode->next
3) Return false

Count the number of nodes :
1) Initialize count as 0
2) Initialize a node pointer, temp = head.
3) Do following while temp is not NULL
     a) temp = temp -> next
     b) count++;
4) Return count

Delete a specific element/node:
1) Find the previous node(prev) of the node to be deleted(temp).
2) Change the next of the previous node, prev->link = temp->link.
3) Free memory for the node to be deleted, delete temp.

Insert after a given node:
Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 <= n.
Examples:
Input : list: 1->3->4->5
        n = 4, x = 2
Output : 1->2->3->4->5
(4th node from the end is 1 and insertion has been done after this node)

Here is the code for the same:-

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

template <typename T>
struct Node {
T data;
Node *link;

   Node(T data=0, Node *p = NULL) { //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
           }
   }
   //Question 2 Starts
   //Adds a node with data at the beginning of the list
   void addFirst(int n){
       if(head==NULL){//check if list is NULL
           head = new Node<T>(n);
           current = head;
       }
       else{
           Node<T> *newNode= new Node<T>(n); //Allocate node
           newNode->link = head; //Link to the head node
           head = newNode; //New head of the list
       }
   }
  
   // Removes the first node of the list.
   void pop(){
       //Declare a temp and point to head
       Node<T> *temp= head;
       //Move the head to next node
       head= head->link;
       //Show the element to be deleted
       cout<<"\nElement to be deleted is : "<<temp->data;
       //Delete temp
       delete temp;
       //Show the new head
       cout<<"\nThe new Head of the List is : "<<head->data;
      
   }
  
   //Returns true or false if a node contains the data
   bool contains(T data)
   {
       Node<T> *temp=head; //initialize loop variable
       while(temp != NULL){
           if(temp->data == data){ //If found return true
               return true;
           }
           temp= temp->link; //move the temp if not found
       }
       return false; //If not found
   }
  
   //Updates the oldData of a node in the list with newData
   void update(T oldData, T newData){
       Node<T> *temp=head; //initialize temporary node as head
       while(temp != NULL){
           if(temp->data == oldData){ //If oldData found change with newData
               temp->data = newData;
           }
           temp= temp->link; //move the temp if not found
       }
   }
  
   //Returns the number of nodes in the list
    int getCount() {
       int count = 0; // Initialize count
       Node<T>* temp = head; // Initialize temporary node
       while (temp != NULL) {
           count++; //Increase count number
           temp = temp->link;
       }
       return count; //Return the total count
   }
  
   //Removes the node that contains the data.
   //Note, you will need to check if the node exists.
   void remove(T data){
       if(head->link == NULL)
        {
            cout << "\nThere is only one node." <<
                    " The list can't be made empty...";
            return;
        }
      
       Node<T> *temp = head; // Initialize temporary node as Head
       Node<T> *prev = temp;
       // Search for the key to be deleted, keep track of the
       // previous node as we need to change 'prev->next'
       while(temp != NULL && temp->data != data){
           temp = temp->link;
       }
      
       // If key was not present in linked list
        if (temp == NULL) return;

       // Unlink the node from linked list
       prev->link = temp->link;

       delete temp; // Free memory
   }
   //Question 2 ends
   //Question 3 starts
  
   //Adds a node after the n-th node. Note, you will
   // need to check if the n th node exists, if not, do addLast()
   void insertAfter(int n, T data){
       // if list is empty, do addLast
       if (head == NULL){
           addLast(data);
       }
      
       // get a new node for data
       Node<T>* newNode = new Node<T>(data);
       Node<T>* ptr = head;
       int len = 0, i;

       // find number of nodes in the list
       while (ptr != NULL) {
            len++;
            ptr = ptr->link;
        }

       // traverse up to the nth node from the end
       ptr = head;
       for (i = 1; i <= (len - n); i++)
           ptr = ptr->link;

       // insert the 'newNode' by making the
        // necessary adjustment in the links
       newNode->link = ptr->link;
       ptr->link = newNode;
   }
  
   //merge(const linked_List &linked_list)
   //Merges this object with linkedlist object, i.e., add all nodes in linkedlist to this object.
   //This is somewhat like copy constructor
   void merge(const linked_list &linkedlist){
       if(linkedlist.head == NULL){
           head=NULL;
       }
       else{
           //passing the data to the head
           head = new Node<T>(linkedlist.head->data);
           Node<T> *cur = head; //current
           Node<T> *listHead = linkedlist.head; //object head
           Node<T> *curList = listHead; //current object
          
           while(curList->link != NULL){
               cur->link = new Node<T>(curList->link->data);
               curList = curList->link; //Shift current object
               cur = cur->link; //Shift current node
           }
       }
   }
  
   //Question 3 ends
   void print() { // to display all nodes in the list
       Node<T> *tmp = head;
       cout<<"\nElements of the List are: ";
       while (tmp != NULL) {
           cout << tmp->data << " ";
           tmp = tmp->link;
       }
       cout<<"\n";
   }
  
};

int main() {
   linked_list<int> a;
   a.addLast(1);
   a.addLast(3);
   a.addLast(4);
   a.addFirst(5);
   a.addFirst(2);
   a.insertAfter(2,6);
   a.insertAfter(3,8);
   a.print();
  
   a.pop();
   cout<<"\nEnter number to check if present : ";
   int search;
   cin>>search;
   if(a.contains(search))
       cout<<"Present";
   else
       cout<<"Not Present";
   cout<<"\n***Updating 3 with value 9***\n";
   a.update(3,9);
   a.print();
   cout<<"\nTotal number of elements in the list: "<<a.getCount();
  
   cout<<"\nEnter element to remove from the list :";
   int x;
   cin>>x;
   a.remove(x);
   a.print();
  
   //Call merge()
   linked_list<int> b=a;
   a.addLast(9);
   cout<<"\nList 1\n";
   a.print();
   cout<<"\nList 2\n";
   b.print();
  
   return 0;
}

Output for the same is:-

Ask doubts in the comment section.

Happy Learning...


Related Solutions

#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...
***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 <iostream> using namespace std; double print_instructions() { cout << "WELCOME TO BandN book stores" <<...
#include <iostream> using namespace std; double print_instructions() { cout << "WELCOME TO BandN book stores" << endl; cout << "Today we have a deal on e-books. Customers will receive a discount off their entire order.." << endl; cout << "The discount is 15% off your total order and cost per book is 8.99." << endl; cout << "Customers who buy 20 or more e-books will receive 20% off instead." << endl; cout << endl; return 0; } int no_of_books() {...
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); }
Debug please. It's in C++ #include<iostream> #include<string> using namespace std; template <class T> double half(int x)...
Debug please. It's in C++ #include<iostream> #include<string> using namespace std; template <class T> double half(int x) { double h = x / 2; return h; } class TuitionBill { friend ostream& operator<<(ostream, TuitionBill); private: string student; double amount; public: TuitionBill(string, double); double operator/(int); }; TuitionBill::TuitionBill(string student, double amt) { student = student; amount = amt; } double TuitionBill::operator/(int factor) { double half = amount / factor; return hafl; } ostream& operator<<(ostream& o, TuitionBill) { o << t.student << " Tuition:...
Can anyone change it to double linked list #include<stdio.h> #include<stdlib.h> #include <iostream> using namespace std; struct...
Can anyone change it to double linked list #include<stdio.h> #include<stdlib.h> #include <iostream> using namespace std; struct Node {     int data;     struct Node* next; }; void printMiddle(struct Node *head) {     struct Node *slow_ptr = head;     struct Node *fast_ptr = head;     if (head!=NULL)     {         while (fast_ptr != NULL && fast_ptr->next != NULL)         {             fast_ptr = fast_ptr->next->next;             slow_ptr = slow_ptr->next;         }         printf("The middle element is [%d]\n\n", slow_ptr->data);     } } void...
#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;...
Program #include<iostream> using namespace std; struct bookRecord //structure definition {             //structure members definition char title[30];...
Program #include<iostream> using namespace std; struct bookRecord //structure definition {             //structure members definition char title[30];             char main_author[30];             int year_publish;             float price; }; int main() {             struct bookRecord book1; // declare structure variable;             //Get data from user             cout<<"Enter book title: ";             cin>>book1.title;             cout<<"Enter main author name: ";             cin>>book1.main_author;                     cout<<"Enter year publish: ";             cin>>book1.year_publish;             cout<<"Enter book price RM: ";             cin>>book1.price;             //Print the information the screen output            ...
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...
#include<stdlib.h> #include<stdio.h> typedef struct node {    void* dataPtr;    struct node* next; } QUEUE_NODE; typedef...
#include<stdlib.h> #include<stdio.h> typedef struct node {    void* dataPtr;    struct node* next; } QUEUE_NODE; typedef struct {    QUEUE_NODE* front;    QUEUE_NODE* rear;    int count; } QUEUE; //Prototype Declarations QUEUE* createQueue(void); QUEUE* destroyQueue(QUEUE* queue); bool dequeue(QUEUE* queue, void** itemPtr); bool enqueue(QUEUE* queue, void* itemPtr); bool queueFront(QUEUE* queue, void** itemPtr); bool queueRear(QUEUE* queue, void** itemPtr); int queueCount(QUEUE* queue); bool emptyQueue(QUEUE* queue); bool fullQueue(QUEUE* queue); /*================= createQueue ================ Allocates memory for a queue head node from dynamic memory and returns...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT