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.
#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;
}
Comments
Leave a comment