2015-12-16 2 views
-1

Я писал код C, чтобы отменить список ссылок. У меня возникла одна проблема. Если я не делаю указатель nextNULL, то моя обратная функция работает нормально, но если я делаю это null, связанный список всегда сохраняет печать в цикле while.Связанный список обратная функция приводит к бесконечному циклу печати

Ниже приведена правильная программа, которая отлично работает. Но если я сделаю *next = NULL, функция отображения сохранит печать в цикле while.

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

struct node { 
    int data; 
    struct node *next; 
} *head; 

/*************************************************************/ 
/*               */ 
/* create - Function to create Nodes and add them at last */ 
/*               */ 
/*************************************************************/ 
int create(int data) 
{ 
    struct node *temp,*ptr = NULL; 
    //int data = 0; 

    ptr = head; 

    //Printf(" Enter the Data for Node : "); 
    //scanf(" %d ", data); 

    temp = (struct node *)malloc(sizeof(struct node)); 

    if (ptr == NULL) { 
     // this is the first node 
     temp->next = NULL; 
     temp->data = data; 
     head = temp; 
    } else { 
     // this is not the first node 
     while (ptr != NULL) { 
      if (ptr->next == NULL) { 
       temp->next = NULL; 
       temp->data = data; 
       ptr->next = temp; 
       break; 
      } 
      ptr = ptr->next; 
     } 
    } 

    return 0; 
} 

/*************************************************************/ 
/*               */ 
/* create_in_front - Function to add Node in Front   */ 
/*               */ 
/*************************************************************/ 
int create_in_front(int data) 
{ 
    struct node *temp,*ptr = NULL; 
    ptr = head; 

    temp = (struct node *)malloc(sizeof(struct node)); 

    if (ptr == NULL) { 
     // this is the first node 
     temp->next = NULL; 
     temp->data = data; 
     head = temp; 
    } else { 
     // this is not the first node 
     temp->next = ptr->next; 
     temp->data = data; 
     head = temp; 
    } 
    return 0; 
} 

/*************************************************************/ 
/*               */ 
/* create_in_between - Function to add Node in between nodes*/ 
/*               */ 
/*************************************************************/ 

int create_in_between(int data,int pos) 
{ 
    struct node *temp, *ptr = NULL; 
    int i = 0; 

    ptr = head; 

    temp = (struct node *)malloc(sizeof(struct node)); 
    temp->data = data; 

    for (i = 0; i < pos; i++) { 
     if (i == pos-1) { 
      temp->next = ptr->next; 
      ptr->next = temp; 
     } 
     ptr = ptr->next; 
    } 
    return 0; 
} 


/*************************************************************/ 
/*               */ 
/* delete_in_between - Function to add Node in between nodes*/ 
/*               */ 
/*************************************************************/ 

delete_in_between(int pos) 
{ 
    struct node *ptr, *prev = NULL; 
    ptr = head; 
    int i = 0; 

    for (i = 0; i < pos; i++) { 
     if (i == pos-1) { 
      prev = ptr->next; 
      free(ptr); 
      break; 
     } 
     prev = ptr; 
     ptr = ptr->next; 
    } 
    return 0; 
} 

/*************************************************************/ 
/*               */ 
/* reverse - Function to reverse link list     */ 
/*               */ 
/*************************************************************/ 

int reverse() 
{ 
    struct node *prev = NULL; 
    struct node *curr = head; 
    struct node *next = NULL; 

    curr = head; 

    while (curr != NULL) { 
     next = curr->next; 
     curr->next = prev; 
     prev = curr; 
     curr = next; 
    } 
    head = prev; 

    return 0; 
} 

/*************************************************************/ 
/*               */ 
/* display - Function to diplay link list     */ 
/*               */ 
/*************************************************************/ 
// Function to display Link List 
int display() 
{ 
    struct node *temp = head; 

    while (temp != NULL) { 
     printf("%d->",temp->data); 
     temp = temp->next; 
    } 
    return 0; 
} 

int main() 
{ 
    create(10); 
    create(20); 
    create(30); 
    create(40); 
    create(50); 
    create_in_front(34); 
    create_in_between(55,2); 
    //delete_in_between(4); 
    reverse(); 
    display(); 
    return 0; 
} 

Позвольте мне знать логику этого.

+4

Пожалуйста, отредактируйте этот вопрос, чтобы опубликовать нерабочий код. Трудно сказать, почему это неправильно, когда мы не можем это увидеть. То есть * где * вы устанавливаете 'next' в' NULL'? Или вы на самом деле делаете '* next = NULL' где-то? – Angew

+2

«Но если я сделаю * next = NULL, функция отображения сохранит печать в цикле while». где? –

+1

Пожалуйста, покажите нам [MCVE] (http://stackoverflow.com/help/mcve). –

ответ

2

Функция create_in_front() является фальшивкой: temp->next = ptr->next; должен быть изменен на temp->next = ptr;

create_in_between() не обрабатывает случай pos==0.

delete_in_between() полностью дисфункциональный: узел свободен, но его предшественник все еще указывает на него.

reverse() кажется правильным для меня, это может быть упрощен следующим образом:

int reverse() { 
    struct node *prev = NULL; 
    struct node *curr = head; 

    while (curr != NULL) { 
     struct node *next = curr->next; 
     curr->next = prev; 
     prev = curr; 
     curr = next; 
    } 
    head = prev; 

    return 0; 
} 

Проблема, кажется, не связана с вашей модификацией функции reverse(), может быть побочным эффектом ошибок в других функциях.

0

Ваша reverse() функция кажется правильной, но остальная часть кода несколько сложна. Попробуйте что-то вроде этого:

void create(int data) { 
    struct node *temp = malloc(sizeof(struct node)); 

    if (temp != NULL) { 
     temp->next = NULL; 
     temp->data = data; 

     if (head == NULL) { // this is the first node 
      head = temp; 
     } else { 
      // this is not the first node 
      struct node *last = head; 

      while (last->next) 
       last = last->next; 

      last->next = temp; 
     } 
    } 
} 

void create_in_front(int data) { 
    struct node *temp = malloc(sizeof(struct node)); 

    if (temp != NULL) { 
     temp->next = head; 
     temp->data = data; 
     head = temp; 
    } 
} 
Смежные вопросы