Visualizzazione dei risultati da 1 a 3 su 3
  1. #1
    Utente di HTML.it
    Registrato dal
    Dec 2008
    Messaggi
    760

    C - Massimo elemento lista in ricorsione

    codice:
    int somma(node *l1,int *max){
    if(l1==NULL) return 0;
    else{
        if(l1->data>(*max)) (*max)=l1->data;
        return somma(l1->next,max);}}
    Vorrei trovare il massimo elemento di una lista in ricorsione,in iterazione va bene,ma qui sono bloccato
    Come posso fare?
    Direi una ricorsione tail?
    Grazie in anticipo

  2. #2
    Premetto che l'ho buttata giù senza pensarci troppo quindi fai attenzioni ad eventuali errori:

    Codice PHP:
    #include <iostream>
    #include <ctime>
    #include <cstdlib>

    using namespace std;

    struct node
    {
        
    int data;
        
    nodenext;
    };

    nodehead NULL;

    void print(nodestart)
    {
        
    nodeiter start;
        
        while(
    iter != NULL)
        {
            
    cout << iter->data << " | ";
            
    iter iter->next;
        }
        
        
    cout << endl;
    }

    void findMax(nodenint** max)
    {
        if(
    == NULL)    
            return;    

        if(*
    max == NULL)    
            *
    max = new int(n->data);    
        else if( 
    n->data > **max)    
            **
    max n->data;                
            
        
    findMax(n->nextmax);
    }

    void f(int** n)
    {
        *
    = new int(10);    
    }

    int main(int argcchar *argv[])
    {

        
    srand( (unsigned)time(0) );
            
        for(
    int i 010i++)
        {
            
    nodenewNode = new node;
            
    newNode->data = (rand() % 10) + 1;
            
    newNode->next head;
            
    head newNode;
        }        
            
        print(
    head);
        
        
    intmax NULL;        
        
    findMax(head, &max);
        
    cout << endl << "Max: " << *max;    
        
        
        
    //******* VERIFICA **********
        
    nodeiter head;
        
    bool ok true;
        while(
    iter != NULL)
        {
            if(*
    max head->data)
            {
                
    ok false;
                break;
            }
            
            
    iter iter->next;
        }
        
        if(
    ok)
            
    cout << " - OK" << endl << endl;
        else
            
    cout << " - NO" << endl << endl;
        
    //*******************************
            
        
    delete max;


  3. #3
    Utente di HTML.it
    Registrato dal
    Dec 2008
    Messaggi
    760
    ti ringrazio davvero tanto antotan sei stato molto gentile
    Ho risolto poco fa con una ricorsione di coda

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.