2013-12-08 100 views
-1

可執行文件突然停止工作。整個程序可以正常工作,但鏈接列表反轉的部分使得exe文件可以這樣做。這段代碼有什麼錯誤?

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

struct node{ 
    int info; 
    struct node *link; 
} *start=NULL; 

main() 
{ 
    int i=1,n,data; 
    printf("\nEnter the number of nodes you want to enter: "); 
    scanf("%d",&n); 
    printf("\nEnter the key no. 1: "); 
    scanf("%d",&data); 
    struct node *p=start,*tmp=(struct node *)malloc(sizeof(struct node)); 
    tmp->info=data; 
    tmp->link=NULL; 
    start=tmp; 
    while(i<n) 
    { 
     printf("\nEnter the key no. %d: ",(i+1)); 
     scanf("%d",&data); 
     while(p!=NULL) 
       p=p->link; 
      tmp->info=data; 
     tmp->link=NULL; 
     p=tmp; 
     i++; 
    } 
    p=start; 
    printf("\nThe list is: "); 
    while(p!=NULL) 
    { 
     printf("%d ",p->info); 
     p=p->link; 
    } 
    p=start; 
    printf("\nThe reversed list is: "); 
    while(p->link->link!=NULL) 
    { 
     p->link->link=p; 
     p=p->link; 
    } 
    start->link=NULL; 
    start=p->link; 
    for(p=start;p!=NULL;p=p->link) 
     printf("%d",p->info); 
    getch(); 
    return 0; //main shourl return. 
} 
+1

到底什麼你問,「讓exe文件這樣做呢?」你的問題標題提到一個錯誤代碼,但你沒有顯示錯誤。請閱讀如何發佈正確的問題。 – OldProgrammer

回答

1

您有:*p=startstart=NULL,然後while(p!=NULL) p=p->link;

我永遠不會發生,因爲p爲空:)

0

你的程序是很容易出錯 最初start==NULL

和聲明1

struct node *p=start,*tmp=(struct node *)malloc(sizeof(struct node)); 這將使p等於NULL

then statement 2:

start=tmp; 

這將更新開始但不會更新p

你應該改掉的聲明1

struct node *tmp=(struct node *)malloc(sizeof(struct node)); 
//processing tmp 
struct node *p=start=tmp 

而且

//at time of insertion

while(p!=NULL) 
     p=p->link; 
    tmp->info=data; 
    tmp->link=NULL; 
    p=tmp; 

手錶while循環清楚,p出來循環的時候才NULL,那麼你要添加到p=tmp(TMP指定爲null)這是非法的

你應該這

while(p->link!=NULL) 
    p=p->link; 
tmp->info=data; 
tmp->link=NULL; 
p->link=tmp;