2017-06-16 80 views
-8

我有一個練習在C中做,我需要一些幫助。我必須編寫一個遞歸函數(checkModOfPrevSum()),它將檢查存儲的數字列表,如果每個值爲node%sum_of_previous_nodes == 0無效函數C遞歸

對於每個節點,它必須打印節點的值,前面節點的總和以及「是」或「否」,具體取決於node_value%sum_of_previous_nodes == 0。打印必須以相反的順序完成。

我要使用的功能是這樣的:

void checkModOfPrevSum(struct list *node, int sum) {.........} 

不允許使用任何同時或循環。

實施例,如果列表低於一個:(節點具有值5是頭部)

5 2 3 6 1 7 4 

其結果必然是:

4 [24] (YES) - 7 [17] (NO) - 1 [16] (YES) - 6 [10] (NO) - 3 [7] (NO) - 2 [5] (NO) - 5 [0] (YES) 

如何可以編寫代碼?

+1

你有沒有嘗試過? :-)如果是這樣,請將其添加到問題中,並嘗試確保它是[mcve]。 – George

+0

歡迎來到StackOverflow。請閱讀並遵守幫助文檔中的發佈準則。 [在主題](http://stackoverflow.com/help/on-topic)和[如何提問](http://stackoverflow.com/help/how-to-ask)適用於此處。 StackOverflow不是一個設計,編碼,研究或教程服務。 – Prune

+1

[「有人能幫助我嗎?」是不是一個有效的SO問題)[https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question)。這通常表明,你需要的是半個小時的時間與當地的導師,或通過一個教程,而不是堆棧溢出。 – Prune

回答

1

我們初學者應該互相幫助。

的分配是不容易做到這樣的初學者作爲你和我。:)

給你。

#include <stdio.h> 
#include <stdlib.h> 

struct node 
{ 
    int data; 
    struct node *next; 
}; 

void insert(struct node **head, const int a[], size_t n) 
{ 
    if (*head != NULL) head = &(*head)->next; 

    for (size_t i = 0; i < n; i++) 
    { 
     struct node *tmp = malloc(sizeof(struct node)); 
     tmp->data = a[i]; 
     tmp->next = *head; 
     *head = tmp; 
     head = &(*head)->next; 
    }   
}  

void checkModOfPrevSum(struct node *head, long long int sum) 
{ 
    if (head != NULL) 
    { 
     if (head->next != NULL) 
     {    
      checkModOfPrevSum(head->next, sum + head->data); 
      printf(" - "); 
     }    

     printf("%d [%lld] (%s)", head->data, sum, sum % head->data == 0 ? "YES" : "NO"); 
    }   
}  


int main(void) 
{ 
    struct node *head = NULL; 
    int a[] = { 5, 2, 3, 6, 1, 7, 4 }; 
    const size_t N = sizeof(a)/sizeof(*a); 

    insert(&head, a, N); 

    checkModOfPrevSum(head, 0); 

    return 0; 
} 

程序輸出是

4 [24] (YES) - 7 [17] (NO) - 1 [16] (YES) - 6 [10] (NO) - 3 [7] (NO) - 2 [5] (NO) - 5 [0] (YES) 

當然的列表實現是不完整的。只要你喜歡,你可以進一步發展。

+0

'if(* head!= NULL)head =&(* head) - > next;'這不應該是'while'? linus風格很難讀:p。 – Stargateur

+0

@Stargateur爲什麼它應該是一段時間?它只是一個語句,用於檢查傳遞的節點是否爲NULL或不是NULL並相應地調整頭。 –

+0

這樣做的目的是什麼?如果不是'while',我不明白你的目標是添加這個if。你想在這個列表的一個元素之後插入? – Stargateur