//09 Find the m-th-to-last element of a linked list
//2011-06-18
#include <iostream>
using namespace std;
struct node{
int data;
node* next;
};
node *head = NULL;
void insertHead(int data){
node *newE = new node;
newE->data = data;
newE->next = head;
head = newE;
}
void printList(node *pos){
node *cursor = pos;
while (cursor){
cout << cursor->data << " ";
cursor = cursor->next;
}
}
node* mthToLast(int m){
node *toReturn = NULL;
node *cursor = head;
int counter = -1;
while (cursor){
if (counter == m){
toReturn = head;
}
if (toReturn) toReturn = toReturn->next;
cursor = cursor->next;
counter++;
}
return toReturn;
}
int main(){
for(int i=0;i<10;i++){
insertHead(i);
}
printList(head);
node *mth = mthToLast(4);
if (mth){
cout << "\nThe 4-th behind element is " << mth->data << "\n";
}
return 1;
}