In: Computer Science
Sample Program:-
#include <iostream>
using namespace std; // Avoid need to use std:: qualification on cout and other things
typedef struct node {
int value;
node* next = NULL;
}node;
node *head = NULL;
int ValueGet(node *head, int index)
{
int count = 0; // The value at index 0 is
pointed.
while(head != NULL) { // Loop through all the element
of the list.
if(count == index) { // Check if we
are pointing the index that we want to get currently.
return
head->value; // If yes then return the value.
}
head = head->next; // If not
correct then we start pointing to the next node.
count++; // Increment the index of
node we are currently pointing.
}
cout << "The index does not exist." <<
endl; // If value is not found then tell that index is
invalid.
return 0;
}
int main() {
node *p1, *p2, *p3, *p4;
int value;
// Creating the linked list as in example.
p1 = (node *)malloc(sizeof(node));
p2 = (node *)malloc(sizeof(node));
p3 = (node *)malloc(sizeof(node));
p4 = (node *)malloc(sizeof(node));
// Setting values and pointers in the list.
head = p1;
p1->value = 01;
p1->next = p2;
p2->value = 100;
p2->next = p3;
p3->value = 300;
p3->next = p4;
p4->value = 214;
value = ValueGet(head, 2); // Getting the value at
index value 2.
cout << value; // Printing the returned
value.
}
Output :-
Hope this helps. If you have any queries or suggestions regarding the answers please leave them in the comments section so I can update and improve the answer. Thank you.