Scrivere una funzione che prese in input
una lista di interi, sommi al valore intero dell’elemento della lista la somma dei valori
interi degli elementi precedenti nella lista.
 
#include <stdio.h>
#include <stdlib.h>
struct nodo{
    
    int elem;
    struct nodo *next;
    };
    
    typedef struct nodo L_ELEM;
    typedef struct nodo *L_PTR;
    
    
void stampa_lista(L_PTR p);
L_PTR inserisci_in_coda(L_PTR L, int val);
L_PTR somma(L_PTR L);
int main()
{
    L_PTR startPtr = NULL;
    int k=0;
    int val=0;
    int z=0;
    scanf("%d",&k);
    z=k;
    while(k>0)
    {
        scanf("%d",&val);
        startPtr = inserisci_in_coda(startPtr, val);
        k--;
    }    
    if (z!=0)
    {
    startPtr = somma(startPtr);
    }    
    stampa_lista(startPtr);
    system("pause");
    return 0;
}
void stampa_lista(L_PTR p) {
  while (p != NULL) {
    printf("%d ", p->elem);
    p = p->next;
  }
  return;
}
L_PTR inserisci_in_coda(L_PTR L, int val)
{
    L_PTR curr,temp;
    curr=L;
        temp = malloc(sizeof(L_ELEM)); 
        
        if(temp != NULL)
        {
            temp->elem = val;
            if (L==NULL)
            {
            temp->next = NULL;
            curr=temp;
            }        
            else
            {    
                 while(L->next != NULL )
                 L=L->next;
                 temp->next=L->next;
                 L->next= temp;
            }
            return curr;
        }    
        else return NULL;       
}
L_PTR somma(L_PTR L)
{
    L_PTR prev,curr,tempPtr;
    
    curr=L;
    prev=curr;
    if (curr->next == NULL)
    return L;
    else
    while(curr != NULL)
    {
    prev=curr;
    curr=curr->next;
    if (curr == NULL)
    return L;    
    curr->elem = prev->elem + curr->elem;
    }        
    return L;
}
Ricerca appunti sul web
 
  
    Ricerca personalizzata
  
sabato 28 febbraio 2009
Sorgenti c : Somma predecessori in una lista
Pubblicato da
Baiox
alle
00:47
        
 
 
Etichette: Informatica, Programmazione C
Iscriviti a:
Commenti sul post (Atom)
0 commenti:
Posta un commento