In this problem, I need to find the nth to the last node data of a singly linked list.
In order to do so, one good way is to use recursion, since it is automatically put recursion part into stack and what we want is to implement LIFO.
So here it comes:
void findn(node* head){
if(head==NULL) return;
//head = head->next; // if use it, output n-1th not nth
findn(head->next);
if(nn==1) pp = head;
--nn;
}
It is very important to fully understand recursion. A good example that I followed is from <Absolute C++, 4th>.
full code comes here, very useful to learn C++. But still lack of use of class...Need to learn it, as well as .h file.
// 2-2 tony
#include
using namespace std;
struct node{
int data;
node* next;
};
node* init(int* a, int n){
node *head, *p;
for (int i=0; idata = a[i];
if(i==0){
head = p = nd;
continue;
}
p->next = nd;
p = nd;
}
return head;
}
void print(node* head){
if(head==NULL) {
cout << "end" << endl;
return; // must add return here so
// as to jump out of recursion
}
cout<data<<"_ ";
head=head->next;
print(head);
}
//
int nn;
node* pp;
//
void findn(node* head){
if(head==NULL) return;
findn(head->next);
if(nn==1) pp = head;
--nn;
}
node* findn1(node *head, int n){
if(head==NULL || n<1) return NULL;
node *p, *q;
p = q = head;
while(n>0 && q){
n--;
q = q->next;
}
if(n>0) return NULL;
while(q){
p=p->next;
q=q->next;
}
return p;
}
int main(){
int n = 10;
int a[] = {
10,9,8,7,6,5,4,3,2,1
};
node* head = init(a,n);
nn = 6;
print(head);
node* p = findn1(head, 6);
if(p) cout<< "solution1: " <data<data << endl;
return 0;
}
/*
node* init(int* a, int n){
node *head, *p = head->next;
if(n==0) return;
else if(n==1) return;
else{
head->data = a[0];
for(int i=1; i< n; ++i){
p->data = a[i]
}
return head;
}
}
*/
Executing the program....
$demo
10_ 9_ 8_ 7_ 6_ 5_ 4_ 3_ 2_ 1_ end
solution1: 6
solution2: 6
void findn(node* head, int depth){
if(head==NULL) return;
findn(head->next, depth-1);
if(depth==1) pp = head; //But the index is wrong
//--depth;
}
Here is the not correct output: should get 6 instead of 5Executing the program....
$demo
10_ 9_ 8_ 7_ 6_ 5_ 4_ 3_ 2_ 1_ end
5