Ch2-2: return the nth to the last node data of a singly linked list

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; i
    
    
     
     data = 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


  
  

I can also have depth variable feed as input to findn() function but should use (depth==2) so as to get the 6th to the last as output instead of 5th. need more deep understanding of recursion: chaining;;;;
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 5
Executing the program....
$demo 
10_ 9_ 8_ 7_ 6_ 5_ 4_ 3_ 2_ 1_ end
5


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值