2016-08-24 3 views
1

リンクリストを逆順で印刷しようとしていますが、実行すると印刷されません。正しい注文を印刷した後に停止し、その後に出力画面がハングアップします。ここに私のコード:リバースリンクリストが逆反復メソッドを使用している間に印刷されない

#include<stdio.h> 
#include<conio.h> 
#include<stdlib.h> 
struct node{ 
    int data; 
    struct node *next; 
}; 
void reverse(struct node*); 
void main() 
{ 
    struct node *a; 
    char ch; 
    struct node *temp; 
    struct node *temp1; 
    a=NULL; 
    clrscr(); 
    do 
    { 
    if(a==NULL) 
    { 
     temp=(struct node*)malloc(sizeof(struct node)); 
     printf("Enter Data"); 
     scanf("%d",&temp->data); 
     temp->next=NULL; 
     a=temp; 
    } 
     else 
    { 
    temp=(struct node*)malloc(sizeof(struct node)); 
    temp->next=NULL; 
    printf("Enter data element"); 
    scanf("%d",&temp->data); 
    temp1=a; 
    while(temp1->next!=NULL) 
     { 
     temp1=temp1->next; 
     } 
    temp1->next=temp; 
    } 
    printf("Do You Wish to continue"); 
    ch=getch(); 
    } 
    while(ch=='Y'||ch=='y'); 
    printf("Status of the link list"); 
    temp1=a; 
    while(temp1!=NULL) 
    { 
    printf("%d ",temp1->data); 
    temp1=temp1->next; 
    } 
    reverse(a); 
    getch(); 
} 
void reverse(struct node *head) 
{ 
struct node *prev,*current,*next,*t; 
current=head; 
prev=NULL; 
while(current!=NULL) 
    { 
    next=current; 
    current->next=prev; 
    prev=current; 
    current=next; 
    } 
head=prev; 
printf("Displaying in reverse order"); 
t=head; 
while(t!=NULL) 
    { 
    printf("%d",t->data); 
    t=t->next; 
    } 

} 

ありがとう!

+3

によって返された値をキャストしないでくださいデバッガを使用して、どのように変数ANその値を監視しながらラインで、あなたのコード行をステップ実行する方法を学びます。 –

+1

'next = current;' - > 'next = current-> next;' – BLUEPIXY

+0

@BLUEPIXYおかげで私は間違いを犯した – user6547375

答えて

4

コードには2つの問題があります。

1)next=current; がメインで、あなたのリストにあなたが失ったreverseを呼び出した後、コメント

2)で@BLUEPIXYで指摘したようにnext=current->next;、すなわちheadあってはならない、もはやリストの先頭を指しています。この問題を解決するには、行うことができます:

struct node* reverse(struct node *head) 
{ 
    .... 
    return head; 
} 

と別の解決策がある

head = reverse(head); 

mainに:head間接参照、その後

void reverse(struct node **head) { ... } 
         ^
          notice 

// Called from main as: reverse(&head); 

との機能で使用する前に。これにより、headmainに変更する機能では、*headに変更されます。

ところで:malloc

関連する問題