Question

In: Computer Science

C++ #include <iostream> using namespace std; struct Node {     int data;     Node* next;   ...

C++

#include <iostream>

using namespace std;

struct Node {
    int data;
    Node* next;
  
    Node(){
        data = 0;
        next = NULL;
    }
  
    Node(int x){
        data = x;
        next = NULL;
    }
};


struct LinkedList {
    Node* head;
  
    LinkedList(){
        head = NULL;
    }
  
    void append(int value){
      
        if (head == NULL){
            head = new Node(value);
        }
        else{
          
            Node* newNode = new Node(value);
          
            Node* temp = head;
            while(temp->next != NULL){
                temp = temp->next;
            }


            temp->next = newNode;
        }
    }
  
    void insertAt(int index, int value) {
        // Provide your code here
    }
  
    int getValue(int index){
        // Provide your code here
    }
  
    void setValue(int index, int value){
        // Provide your code here
    }
  
    void print (){
        Node* temp = head;
      
        while (temp != NULL) {
            cout << temp->data << endl;
            temp = temp->next;
        }
    }
  
    ~LinkedList(){
        Node* temp = head;
      
        while(temp != NULL){
            temp = temp->next;
            delete head;
            head = temp;
        }
    }
};


int main(int argc, const char * argv[]) {
  
    LinkedList myList;
  
  
    for (int i = 0; i < 6; i++) {
        myList.append(i);
    }
  
    myList.insertAt(2, 77);
  
    myList.insertAt(10, 89);
  
    myList.append(101);
  
    myList.setValue(0, 11);
  
    cout << myList.getValue(2) << endl << endl;
  
    myList.print();
  
    //    Expected output:
    //    77
    //
    //    11
    //    1
    //    77
    //    2
    //    3
    //    4
    //    5
    //    0
    //    0
    //    0
    //    89
    //    101
  
    return 0;
}

The first function you are being asked to implement is int getValueAt(int index) . This function simply returns the value that appears in the array position specified by index .

The second function is void setValueAt(int index, int value) . Its job is to store value in the array position corresponding to index .

The last function to implement is void insertAt(int index, int value) . As the name suggests, it needs to insert the value at the index. It should not overwrite anything. If there is already a something stored at index , it should be shifted to the right. If index is larger than the current size of the list, then it needs to be resized in order to accomodate. If there is a gap between the old size of the list, and the newly inserted value, that gap should be filled with 0s

Solutions

Expert Solution

#include <iostream>

using namespace std;

struct Node {
    int data;
    Node* next;

    Node(){
        data = 0;
        next = NULL;
    }

    Node(int x){
        data = x;
        next = NULL;
    }
};


struct LinkedList {
    Node* head;

    LinkedList(){
        head = NULL;
    }

    void append(int value){

        if (head == NULL){
            head = new Node(value);
        }
        else{

            Node* newNode = new Node(value);

            Node* temp = head;
            while(temp->next != NULL){
                temp = temp->next;
            }


            temp->next = newNode;
        }
    }

    void insertAt(int index, int value) {
    Node *x = new Node;
    x->data = value;
    x->next = NULL;

    if(index == 0) {
        x->next = head;
        head = x;
    } else {
        index--;
        Node *y = head;
        while(y->next && index != 0) {
            y = y ->next;
            index--;
        }   

        if(index == 0) {
            x->next = y->next;
            y->next = x;
        } else {
            // add new nodes.
            while(index != 0) {
                y->next = new Node(0);
                y = y->next;
                index--;
            }
            y->next = new Node(value);

        }

    }
    }

    int getValue(int index){
    Node *y = head;
    while(y && index != 0) {
        y = y ->next;
        index--;
    }   

    if(y == NULL) {
        // invalid index
        return -1;
    } else {
        return y->data;
    }
    }

    void setValue(int index, int value){
    Node *y = head;
    while(y && index != 0) {
        y = y ->next;
        index--;
    }   

    if(y == NULL) {
        // invalid index
        return;
    } else {
        y->data =value;
    }
    }

    void print (){
        Node* temp = head;

        while (temp != NULL) {
            cout << temp->data << endl;
            temp = temp->next;
        }
    }

    ~LinkedList(){
        Node* temp = head;

        while(temp != NULL){
            temp = temp->next;
            delete head;
            head = temp;
        }
    }
};


int main(int argc, const char * argv[]) {

    LinkedList myList;


    for (int i = 0; i < 6; i++) {
        myList.append(i);
    }

    myList.insertAt(2, 77);

    myList.insertAt(10, 89);

    myList.append(101);

    myList.setValue(0, 11);

    cout << myList.getValue(2) << endl << endl;

    myList.print();

    //    Expected output:
    //    77
    //
    //    11
    //    1
    //    77
    //    2
    //    3
    //    4
    //    5
    //    0
    //    0
    //    0
    //    89
    //    101

    return 0;
}

Please upvote, as i have given the exact answer as asked in question. Still in case of any concerns in code, let me know in comments. Thanks!


Related Solutions

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...
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); }
#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;...
#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';     }      ...
FINISH print and freelist #include<stdio.h> #include <stdlib.h> struct node {      int data;      struct node  *next; }; struct...
FINISH print and freelist #include<stdio.h> #include <stdlib.h> struct node {      int data;      struct node  *next; }; struct node* insert(struct node* list,int d ); struct node* del(struct node* list,int d ); void print( struct node *list); void freeList(struct node* list); void copy ( struct node *q, struct node **s ); int main( ) {     int number = 0, choice = 0;     struct node *pList=NULL;     struct node *nList = NULL;         while(choice!= 4)     {                 printf("Do you want to (1)insert, (2)delete, (3)Copy (4)quit.\n");...
in C++, #include<iostream> using namespace std; const int NUM = 10; void prepareArr(int a[]); int countEven...
in C++, #include<iostream> using namespace std; const int NUM = 10; void prepareArr(int a[]); int countEven (int b[]); int main() { int arr[NUM]; // write a statement to call prepareArr to set values for the array // write a statement to call countEven and print the data returned for(int i = 0; i<NUM; i++) cout << arr[i] <<" "; cout <<endl; return 0; } void prepareArr(int a[]) { //randomly generate NUM integers in the range [0,99] and save them in...
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...
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 <iostream> #include <string> #include <iomanip> #include <fstream> using namespace std; struct Product {    string...
#include <iostream> #include <string> #include <iomanip> #include <fstream> using namespace std; struct Product {    string itemname;    int id;    string itemcolor;    double cost; }; void fillProduct(Product[10], int& );//read data from a file and store in an array void writeProduct(Product[10], int);//write the array into a file void writeBinary(Product[10], int);//write the array into a file in binary mode void printbinary(Product[10], int);//read data from the binary file and print int main() {    Product myList[10];    int numItems = 0;...
#include <iostream> using namespace std; int main() {     int hour;     int min;     for (hour = 1;...
#include <iostream> using namespace std; int main() {     int hour;     int min;     for (hour = 1; hour <= 12; hour++)     {         for (min = 0; min <= 59; min++)         {             cout << hour << ":" << min << "AM" << endl;         }     }       return 0; } 1.      Type in the above program as time.cpp. Add a comment to include your name and date. Compile and run. 2.      What is the bug or logic error in the above program? Add the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT