﻿ Linked list nth last element ~ Programming Tutorials by SourceTricks
Monday, July 16, 2012

## Linked list nth last element

### Write a program to find in a linked list nth last element

The approach:-
1. Maintain 2 pointers to head of the list.

2. Move 1st pointer n - 1 elements.

3. Now move both the pointers until one of them hits the end of list.

4. Return the other pointer which would point in the linked list nth element from last.

#### C++ program to find a linked list nth last element

```#include <iostream>
using namespace std;

// Node class
class Node {
private:
int mData;
Node* mNext;
public:
Node() { mNext = NULL; }
~Node() {}
int data() { return mData; }
Node* next() { return mNext; }
void setData(int data) { mData = data; }
void setNext(Node* next) { mNext = next; }
};

// List class
class List {
private:
public:
List() { head = NULL; }

~List() {}

if ( head == NULL ) {
Node* tmp = new Node();
tmp->setData(data);
}
else {
while ( tmp->next() != NULL )
tmp = tmp->next();

Node* tmp1 = new Node();
tmp1->setData(data);
tmp->setNext(tmp1);
}
}

friend ostream& operator << (ostream& o, const List& l) {
while ( tmp != NULL ) {
cout << tmp->data() << " ";
tmp = tmp->next();
}
return o;
}

Node* fromLast(int n) {
// 2 pointers to the list head

// Move second pointer 'n-1' places from start
int count = n - 1;
while ( tmp2 != NULL && count-- >= 0 ) {
tmp2 = tmp2->next();
}

// Move both pointers till end of list
while ( tmp2 != NULL ) {
tmp2 = tmp2->next();
tmp1 = tmp1->next();
}

// return the first pointer
return tmp1;
}
};

// Test program
int main() {
List* l = new List();

for ( int i = 1; i <= 10; i++ )

cout << *l << endl;
cout << l->fromLast(4)->data() << endl;

delete l;
}```

Output:-
```100 200 300 400 500 600 700 800 900 1000
700```

Name

Email *

Message *