2013-11-28 21 views
0
#include<stdio.h> 
#include<stdlib.h> 

struct nodetag{ 
    int ndata; 
    struct nodetag *pNext; 
}; 
typedef struct nodetag nodetag; 

int main(){ 
    nodetag *p1=NULL,*bago,*last,*ptemp; 
    int i,x,y; 

    printf ("\nEnter number of nodes: "); 
    scanf ("%d", &i); 
    y=i; 

    while (i) 
    { 
     if (p1 == NULL) 
     { 
      p1 = malloc(sizeof(nodetag)); 
      last = p1; 
      p1->pNext = NULL; 
      scanf("%d",&p1->ndata); 
     } 
     else 
     { 
      bago = malloc(sizeof(nodetag)); 
      last->pNext = bago; 
      bago->pNext = NULL; 
      scanf("%d",&bago->ndata); 
     } 
     i--; 
    } 

    ptemp = p1; 
    for(x=0;x<y;x++){ 
     printf("%d",ptemp->ndata); 
     ptemp=ptemp->pNext; 
    } 
    getch(); 
    return 0; 
} 

我可以將整個節點複製到ptemp以避免pfirst被移動? 當我運行代碼時,它似乎只打印節點的第一個和最後一個數據。 節點數超過2個時,如何訪問第二個節點? IM重點的節點打印數據C中的鏈表可以將整個節點複製到ptemp

ptemp = p1; 
for(x=0;x<y;x++){ 

    printf("%d",ptemp->ndata); 
    ptemp=ptemp->pNext; 

這似乎是它崩潰的整個程序

回答

3

bago->pNext = NULL;

在此之後添加此行:

last = bago;

現在代碼中的錯誤:

  1. 您還沒有更新last指針,因此每一次分配是分配第二值覆蓋的值。
  2. 你從來沒有free d malloc d內存,在退出main()之前通過迭代列表中的所有內存,就像您在打印時一樣。
  3. getch()不是一個標準庫函數,因此不便於攜帶,你應該使用getchar()代替。

編輯:(在OP的評論)

好,儘量自己瞭解它,它很簡單。手動/手動執行代碼。

+0

你能解釋一下,對我而且謝謝它使它成功! :「> – PNC

+0

是的,現在我明白了,你指出」最後一個「指針 – PNC

2
else 
    { 
     bago = malloc(sizeof(nodetag)); 
     last->pNext = bago; 
     bago->pNext = NULL; 
     scanf("%d",&bago->ndata); 
     last = last->pNext; /*you need add this statements*/ 
     } 

對不起,我的英文不好。 我無法用英文解釋。

相關問題