Monday, January 18, 2021

Access nth element from a linked list

#include <iostream>

#include <bits/stdc++.h>

#include <assert.h>

using namespace std;


class Node{

    public:

    int data;

    Node* next;

    

};


//funtion to push data to the nodes

void push(Node** head_ref, int new_data){

    Node* new_node= new Node();  //node is allocated

    new_node-> data= new_data;   //data is given to node

    new_node->next= (*head_ref);  //link the old list off the new node

    (*head_ref)= new_node;        //move the head to pont to the new node

    

    

}


int getnth(Node* head, int index){

    Node* current= head;

    

    int count=0;

    while(current!=NULL){

        if(count==index)

        return(current->data);

        count++;

        current= current->next;

    }

    assert(0);

}






int main() {

Node* head= NULL;

push(&head, 1);

push(&head, 4);

push(&head, 1);

push(&head, 12);

push(&head, 1);

cout<<getnth(head, 3)<<endl;

return 0;

}


0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home