Answer to Question #270710 in C++ for osama

Question #270710

Write a function that returns the info of the kth element of the singly linked list. If no such element exists, terminate the program also give main.


1
Expert's answer
2021-11-24T00:41:28-0500
#include <iostream>
using namespace std;
class Node{
    public:
    int data;
    Node *next, *prev;
    Node();
    Node(int);
};
Node::Node(){
    next = NULL;
    prev = NULL;
}
Node::Node(int data){
    this->data = data;
    next = NULL;
    prev = NULL;
}
class LL{
    Node *head; 
    int size;


    public:
    LL();
    void insert(int);
    void remove(int);
    int returnKthElement(int);
    void print();
};
LL::LL(){
    size = 0;
    head = NULL;
}
void LL::insert(int data){
    Node *temp = new Node(data);
    Node *curr = head;
    if(curr == NULL){
        temp->next = head;
        head = temp;
        return;
    }
    while(curr->next != NULL){
        curr = curr->next;
    }
    temp->next = curr->next;
    curr->next = temp;
    size++;
}
void LL::remove(int data){
    Node* curr = head;
    Node* prev = NULL;
    Node* temp = NULL;
    while(curr != NULL){
        if(curr->data == data){
            if(prev == NULL){
                temp = head;
                head = head->next;
                curr = head;
                delete temp;
                size--;
            }
            else{
                temp = curr;
                if(curr->next != NULL){
                    prev->next = curr->next;
                }
                else{
                    prev->next = NULL;
                }
                curr = curr->next;
                delete temp;
                size--;
            }
        }
        else{
            prev = curr;
            curr = curr->next;
        }
    }
}


int LL::returnKthElement(int k){
    if(k >= size){
        cout<<"(Position does not exist)";
        return INT_MIN;
    }
        
    int i = 1;
    Node *curr = head;
    while(i < k){
        curr = curr->next;
        i++;
    }
    return curr->data;
}


int main(){
    LL list;
    for(int i = 0; i < 10; i++){
        list.insert(i);
    }


    cout<<"2nd Element: "<<list.returnKthElement(2)<<endl;
    cout<<"20th Element: "<<list.returnKthElement(20)<<endl;
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS