Write a program to find in a linked list nth last element
The approach:-- Maintain 2 pointers to head of the list.
- Move 1st pointer n - 1 elements.
- Now move both the pointers until one of them hits the end of list.
- 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: Node* head; public: List() { head = NULL; } ~List() {} void addNode(int data) { if ( head == NULL ) { Node* tmp = new Node(); tmp->setData(data); head = tmp; } else { Node* tmp = head; 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) { Node* tmp = l.head; while ( tmp != NULL ) { cout << tmp->data() << " "; tmp = tmp->next(); } return o; } Node* fromLast(int n) { // 2 pointers to the list head Node* tmp1 = head; Node* tmp2 = 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(); // Add some random nodes for ( int i = 1; i <= 10; i++ ) l->addNode(i*100); cout << *l << endl; cout << l->fromLast(4)->data() << endl; delete l; }Output:-
100 200 300 400 500 600 700 800 900 1000 700
0 comments:
Post a Comment