Print nth element in linked list using recursion

Actually I was required to only print out every other element in a linked list using recursion but I am very curious if I can use recursion to print out nth element from a linked list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
linked list has n elements

int element(int current*)
{
 current = first

 if(current -> next == NULL)
 {
    cout<<current->info;
 }
 else
 {
    return element(current = current -> link -> link->info);
 }
}
Last edited on
You want to print the nth element of a list which has n elements? That translates into, print the last element, doesn't it?

Something of this style perhaps - not tested:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void print_last_element(int current* = nullptr)
{
    if (current == nullptr)
        current = first;

    if (current->next == nullptr)
    {
        cout << current->info;
    }
    else
    {
        print_last_element(current->next);  
    }
}

Keep count, if you need to count to n:
1
2
3
4
5
6
7
8
9
void foo( N* p, int count ) {
  // code
  if ( 0 == count ) {
    cout << p->bar;
    return;
  }
  // code
  foo( p->next, count - 1 );
}
Topic archived. No new replies allowed.