2013-12-08 101 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;