2013-01-09 67 views
1

我必須爲作業2鏈接列表做準備,將第一個用戶給出的整數放在第一個中,然後將第一個到第二個列表中的每個整數的結果放在結果= x^3中。在下面的代碼中,我試圖打印我放入第一個列表中的內容,並使用scanf進行閱讀。我還沒有理解爲什麼我不能通過這種方式打印。你能解釋一下嗎?提前致謝!!問題是,我只打印最後一個元素和0 ...:■在c中打印鏈接列表

代碼:

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

struct L1 
{ 
    int x; 
    struct L1 *next1; 
}; 

struct L2 
{ 
    int x,i,v; 
    struct L2 *next2; 
}; 

int main() 
{ 
    int i,N; 
    struct L1 *root1; 
    struct L2 *root2; 
    struct L1 *conductor1; 
    struct L2 *conductor2; 

    root1 = malloc(sizeof(struct L1)); 
    root2 = malloc(sizeof(struct L2)); 
    root1->next1=0; 
    conductor1 = root1; 
    printf("Dwste arithmo N"); 
    scanf("%d",&N); 
    printf("\nDwse arithmo"); 
    scanf("%d",&conductor1->x); 
    printf("%d",conductor1->x); 

    for(i=0; i<N; i++) 
    { 
     conductor1->next1 = malloc(sizeof(struct L1)); 
     printf("\nDwste arithmo"); 
     scanf("%d",&conductor1->x); 
     conductor1->next1=0; 
    } 
    conductor1 = root1; 
    while (conductor1 != NULL) 
    { 
     printf("\n%d",conductor1->x); 
     conductor1=conductor1->next1; 
    } 

    return 0; 
} 
+2

您究竟遇到什麼問題?不會編譯,崩潰,錯誤信息? – antlersoft

+0

是啊我編輯它xD對不起.. – alex777

回答

3

for循環,你永遠不會改變的conductor1值。所以它總是指向頭節點,並且你總是會覆蓋該節點的字段。在每次迭代中分配新節點前進到下一個節點後,您需要添加conductor1=conductor1->next1;

+0

改變它,你的意思是? conductor1 = conductor1-> NEXT1; – alex777

+0

@ alex777:是的,在'malloc'之後。 – interjay

+0

哦thx ..就是這樣! – alex777