2016-08-24 74 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

投返回的值了解如何使用调试器,以及如何通过线通过您的代码行的方式执行,同时监测变量的它们的值。 –

+1

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

+0

@BLUEPIXY谢谢我收到了错误 – user6547375

回答

4

您有两个代码问题。

1)next=current;next=current->next;在评论

2)所指出的@BLUEPIXY调用reverse你失去了你的名单后,即head在主不再指向列表的头部。为了解决这个问题,你可以这样做:

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

main

head = reverse(head); 

另一种解决方案是:

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

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

,然后间接引用head在功能使用前。这将更改*head的功能,以更改headmain

BTW:不要通过malloc