2011-04-13 24 views
1

我正在C中使用單個鏈表計算器(是的,它是作業)。我有添加功能「工作」,但由於某種原因,我只能添加兩個相同長度的值。我真的不知道如何添加像12 + 128.目前我的代碼只接受120 + 128.我做錯了什麼,我該如何解決這個代碼?在鏈接列表計算器中添加值

struct digit* add(struct digit *x, struct digit *y) 
{ 
    int carry = 0; 
    struct digit *xHead; 
    struct digit *yHead; 
    struct digit *totalHead; 
    struct digit *current_Digit; 

    xHead = x; 
    yHead = y; 
    totalHead = NULL; 


    while(x != NULL && y != NULL) 
    { 
     current_Digit = (struct digit *)malloc(sizeof(struct digit)); 
     current_Digit->value = x->value + y->value + carry; 

     //calculates the carry 
     carry = 0; 
     if(current_Digit->value > 9) 
     { 
      carry = 1; 
      current_Digit->value = current_Digit->value % 10; 
     } 
     else 
     { 
      carry = 0; 
     } 
     current_Digit->next = totalHead; 
     totalHead = current_Digit; 

     x = x->next; 
     y = y->next; 
    } 
    return totalHead; 
} 
+0

你的struct digit看起來像什麼? – BlackBear 2011-04-13 18:04:58

+0

結構數字 { int value; // data struct digit * next; //下一個指針 }; – user706553 2011-04-13 18:06:30

回答

3

而是同時要x->nexty->next,你的函數應該做到以下幾點:

while (x != NULL || y != NULL) { 
    // malloc 

    current_Digit->value = (x ? x->value : 0) 
         + (y ? y->value : 0) 
         + carry; 

    // compute 

    if (x) x = x->next; 
    if (y) y = y->next; 
} 

(它還看來,如果你向後構建你的結果...)

+0

當我這樣做。 120 + 100 = 120. 100 + 120 = 100。對不起,我對這個東西真的很陌生,這個「簡單」的問題讓我很頭疼!感謝您的幫助。 – user706553 2011-04-13 18:24:20

+0

@ user706553:我忘記了一些括號。你能再次檢查嗎? – 2011-04-13 18:26:01

+0

@ user706553你似乎在從右到左建立'totalHead',這與你閱讀'x'和'y'的方式是相反的。也就是說,你的輸入看起來像是「8-> 2-> 1」,但是你的輸出被構造爲數字128的「1-> 2-> 8」。 – chrisaycock 2011-04-13 18:28:16

2

您目前正在遞增兩個參數的數字,而沒有查看是否已經擊中了其中一​​個參數的末尾。你需要做一個特殊的測試,如果只有一個鏈表在它的末尾,那麼不要增加它,只是假設它的數字值爲零。

所以12 + 128應該動態製作爲[0]12 + 128。您必須添加邏輯以確認在這種情況下x的值已達到其數字的末尾,但y尚未。所以繼續與yx數字召喚零。

+0

只是爲了澄清,那個特殊的測試用例會在while循環之外,檢查它們是否都是NULL,對嗎? – user706553 2011-04-13 18:18:27

+0

@ user706553測試在while循環中。查看@larsman的示例代碼。 – chrisaycock 2011-04-13 18:19:52

+0

刪除我的帖子,解開-1。它確實看起來像OP正在向後建立結果,這可能是也可能不是。 – 2011-04-13 18:21:27

0

您應該確保xy具有相同的位數,否則最終將設置爲NULL。在添加之前,找到最短的零並添加零,直到匹配另一個的長度爲止