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