2016-03-20 4 views
-1

Я пытаюсь создать базу данных обследований, в которых связанный список хранит опросы на основе одной из своих переменных. В тот момент, когда я сортирую опрос, он только помещает узел, отсортированный после первого узла (голова может быть 999 и еще первый узел), а также я вижу случайную бесконечную печать элементов при добавлении элемента, а затем отображение всех элементов.Сортировка связанного списка на основе переменной C

Sample Code: 


void addElement(struct listelement** head_ptr) 
{ 
    int data; 
    int inputPPS; 
    struct listelement *temp; 
    struct listelement *newNode; 



    if (*head_ptr == NULL) 
    { 

     addElement_AtStart(head_ptr); 

    } 

    else 

    { 

     temp = *head_ptr; 
     newNode = (struct listelement*)malloc(sizeof(struct listelement)); 

     printf("\nPlease enter your PPS number (Number must be unique)\n"); 
     scanf("%d", &inputPPS); 
     if (checkUnique(head_ptr, inputPPS) == 1) { 

      newNode->surveyDetails.ppsNo = inputPPS; 
      printf("\nPlease enter your first name:"); 
      scanf("%s", newNode->surveyDetails.fName); 
      printf("\nPlease enter your last name:"); 
      scanf("%s", newNode->surveyDetails.lName); 
      //printf("\nEnter email address: "); 
      //do email validation 
      //scanf("%s", newNode->studentData.email); 

      printf("\nEnter current address: "); 
      scanf(" %s", newNode->surveyDetails.address);//takes in the next 99 characters until a newline is found 

      printf("\nPlease enter your :"); 
      scanf("%d", &newNode->surveyDetails.age); 
      printf("\nPlease enter your yearly salary (as whole number):"); 
      scanf("%d", &newNode->surveyDetails.income); 
      printf("\nHow many cigarrettes do you smoke a day? :"); 
      scanf("%d", &newNode->surveyDetails.ciggiesSmoked); 
      printf("\nHow many units of alcohol do you drink in a day? :"); 
      scanf("%d", &newNode->surveyDetails.unitsTaken); 
      printf("\nHow many time do you exercise every week? :"); 
      scanf("%d", &newNode->surveyDetails.timesExercised); 


      while (temp != NULL) 
      { 
       if (sortedInsert(&head_ptr, newNode) == 1) { 
        printf("\nSurvey stored successfully\n"); 
        break; 
       } 
       temp = temp->next; 

      } 

      //printf("\nSurvey didnt work successfully\n"); 


      //do sorted insert 
     } 
     else {//if pps is not unique recursively start function again prompting user 
      printf("\nWe still value your feedback on this topic! If you believe you have entered your PPS incorrectly you can now try again!"); 
      addElement(head_ptr); 
     } 

    } 
} 

void addElement_AtStart(struct listelement** head_ptr) 
{ 

    struct listelement *newNode; 
    int inputPPS; 

    newNode = (struct listelement*)malloc(sizeof(struct listelement)); 

    printf("\nWe will now take details from you for the survery...\n"); 
    printf("\nPlease enter your PPS number (Number must be unique)\n"); 
    scanf("%d", &inputPPS); 
    if (checkUnique(head_ptr, inputPPS) == 1) { 
     newNode->surveyDetails.ppsNo = inputPPS; 
     //do unique check 
     printf("\nPlease enter your first name:"); 
     scanf("%s", newNode->surveyDetails.fName); 
     printf("\nPlease enter your last name:"); 
     scanf("%s", newNode->surveyDetails.lName); 
     printf("\nEnter email address: "); 
     //do email validation 
     //scanf("%s", newNode->studentData.email); 

     printf("\nEnter current address: "); 
     scanf(" %s", newNode->surveyDetails.address);//takes in the next 99 characters until a newline is found 

     printf("\nPlease enter your age:"); 
     scanf("%d", &newNode->surveyDetails.age); 
     printf("\nPlease enter your yearly salary (as whole number):"); 
     scanf("%d", &newNode->surveyDetails.income); 
     printf("\nHow many cigarrettes do you smoke a day? :"); 
     scanf("%d", &newNode->surveyDetails.ciggiesSmoked); 
     printf("\nHow many units of alcohol do you drink in a day? :"); 
     scanf("%d", &newNode->surveyDetails.unitsTaken); 
     printf("\nHow many time do you exercise every week? :"); 
     scanf("%d", &newNode->surveyDetails.timesExercised); 
    } 
    else {//if pps is not unique recursively start function again prompting user 
     printf("\nWe still value your feedback on this topic! If you believe you have entered your PPS incorrectly you can now try again!"); 
     addElement_AtStart(head_ptr); 
    } 


    //no sorted insert if file has surveys sorting will be done in addElement 

    newNode->next = *head_ptr; 

    *head_ptr = newNode; // transfer the address of newNode' to'head' 

} 
int sortedInsert(struct listelement** head_ref, struct listelement* newNode) 
{ 
    struct listelement* temp; 
    /* Special case for the head end */ 
    if (*head_ref == NULL || (*head_ref)->surveyDetails.ppsNo >= newNode->surveyDetails.ppsNo) 
    { 
     newNode->next = *head_ref; 
     *head_ref = newNode; 
     printf("At head"); 
     return 1; 
    } 
    else 
    { 
     /* Locate the node before the point of insertion */ 
     temp = *head_ref; 
     while (temp->next != NULL && 
      temp->next->surveyDetails.ppsNo < newNode->surveyDetails.ppsNo) 
     { 
      temp = temp->next; 
     } 
     newNode->next = temp->next; 
     temp->next = newNode; 
     return 1; 
    } 
    printf("failed"); 
} 
int checkUnique(struct listelement *head_ptr, int inputPPS) { 
    int nodeNum = 0; 
    struct listelement *temp; 
    temp = head_ptr; 



    while (temp != NULL) 
    { 
     if (nodesAdded == 0) { 
      nodesAdded++; 
      printf("\n First node so is unique"); 
      return 1; 
     } 
     if (temp->surveyDetails.ppsNo== inputPPS) 
     { 
      printf("\n There is a user in the survey system with this PPS Number."); 
      return 0; 
     } 
     nodeNum++; 
     temp = temp->next; 
    } 
    printf("\nPPS Number is unique. Continuing...\n We will now ask you for your survey details... "); 

    nodesAdded++; 
    return 1; 

} 

Edit: Пересмотренный код до сих пор, в данный момент я имею вопрос, где переменные берутся в однако узел не правильно назначен в качестве головного узла, было найдено, что при отладке, где после добавления второй элемент head_ptr имел бы странные значения (а не те, которые были введены).

void addElement(struct listelement** head_ptr) 
{ 
    int data; 
    int inputPPS; 
    struct listelement *temp; 
    struct listelement *newNode; 



    if (*head_ptr == NULL) 
    { 

     addElement_AtStart(head_ptr); 

    } 

    else 

    { 

     temp = *head_ptr; 
     newNode = (struct listelement*)malloc(sizeof(struct listelement)); 

     printf("\nPlease enter your PPS number (Number must be unique)\n"); 
     scanf("%d", &inputPPS); 
     if (checkUnique(&head_ptr, inputPPS) == 1) { 

      newNode->surveyDetails.ppsNo = inputPPS; 
      printf("\nPlease enter your first name:"); 
      scanf("%s", newNode->surveyDetails.fName); 
      printf("\nPlease enter your last name:"); 
      scanf("%s", newNode->surveyDetails.lName); 
      //printf("\nEnter email address: "); 
      //do email validation 
      //scanf("%s", newNode->studentData.email); 

      printf("\nEnter current address: "); 
      scanf(" %s", newNode->surveyDetails.address);//takes in the next 99 characters until a newline is found 

      printf("\nPlease enter your :"); 
      scanf("%d", &newNode->surveyDetails.age); 
      printf("\nPlease enter your yearly salary (as whole number):"); 
      scanf("%d", &newNode->surveyDetails.income); 
      printf("\nHow many cigarrettes do you smoke a day? :"); 
      scanf("%d", &newNode->surveyDetails.ciggiesSmoked); 
      printf("\nHow many units of alcohol do you drink in a day? :"); 
      scanf("%d", &newNode->surveyDetails.unitsTaken); 
      printf("\nHow many time do you exercise every week? :"); 
      scanf("%d", &newNode->surveyDetails.timesExercised); 


      while (temp != NULL) 
      { 
       if (sortedInsert(head_ptr, newNode) == 1) { 
        printf("\nSurvey stored successfully\n"); 
        break; 
       } 
       temp = temp->next; 

      } 

      //printf("\nSurvey didnt work successfully\n"); 


      //do sorted insert 

     } 
     else if (checkUnique(&head_ptr, inputPPS) == 0){//if pps is not unique recursively start function again prompting user 
      printf("\nWe still value your feedback on this topic! If you believe you have entered your PPS incorrectly you can now try again!"); 
      free(newNode); 
     } 

    } 
} 

void addElement_AtStart(struct listelement** head_ptr) 
{ 

    struct listelement *newNode; 
    int inputPPS; 

    newNode = (struct listelement*)malloc(sizeof(struct listelement)); 

    printf("\nWe will now take details from you for the survery...\n"); 
    printf("\nPlease enter your PPS number (Number must be unique)\n"); 
    scanf("%d", &inputPPS); 
    if (checkUnique(head_ptr, inputPPS) == 1) { 
     newNode->surveyDetails.ppsNo = inputPPS; 
     //do unique check 
     printf("\nPlease enter your first name:"); 
     scanf("%s", newNode->surveyDetails.fName); 
     printf("\nPlease enter your last name:"); 
     scanf("%s", newNode->surveyDetails.lName); 
     printf("\nEnter email address: "); 
     //do email validation 
     //scanf("%s", newNode->studentData.email); 

     printf("\nEnter current address: "); 
     scanf(" %s", newNode->surveyDetails.address);//takes in the next 99 characters until a newline is found 

     printf("\nPlease enter your age:"); 
     scanf("%d", &newNode->surveyDetails.age); 
     printf("\nPlease enter your yearly salary (as whole number):"); 
     scanf("%d", &newNode->surveyDetails.income); 
     printf("\nHow many cigarrettes do you smoke a day? :"); 
     scanf("%d", &newNode->surveyDetails.ciggiesSmoked); 
     printf("\nHow many units of alcohol do you drink in a day? :"); 
     scanf("%d", &newNode->surveyDetails.unitsTaken); 
     printf("\nHow many time do you exercise every week? :"); 
     scanf("%d", &newNode->surveyDetails.timesExercised); 
    } 
    else {//if pps is not unique recursively start function again prompting user 

     printf("\nWe still value your feedback on this topic! If you believe you have entered your PPS incorrectly you can now try again!"); 
     free(newNode); 

    } 


    //no sorted insert if file has surveys sorting will be done in addElement 

    newNode->next = *head_ptr; 

    *head_ptr = newNode; // transfer the address of newNode' to'head' 


    free(newNode); 
} 
int sortedInsert(struct listelement** head_ref, struct listelement* newNode) 
{ 
    struct listelement* temp; 
    /* Special case for the head end */ 
    if (*head_ref == NULL || (*head_ref)->surveyDetails.ppsNo >= newNode->surveyDetails.ppsNo) 
    { 
     newNode->next = *head_ref; 
     *head_ref = newNode; 
     printf("At head"); 
     return 1; 
    } 
    else 
    { 
     /* Locate the node before the point of insertion */ 
     temp = *head_ref; 
     while (temp->next != NULL && 
      temp->next->surveyDetails.ppsNo < newNode->surveyDetails.ppsNo) 
     { 
      temp = temp->next; 
     } 
     newNode->next = temp->next; 
     temp->next = newNode; 
     return 1; 
    } 
    printf("failed"); 
} 
int checkUnique(struct listelement *head_ptr, int inputPPS) { 
    int nodeNum = 0; 
    struct listelement *temp; 
    temp = head_ptr; 



    while (temp != NULL) 
    { 
     if (nodesAdded == 0) { 
      nodesAdded++; 
      printf("\n First node so is unique"); 
      return 1; 
     } 
     if (temp->surveyDetails.ppsNo== inputPPS) 
     { 
      printf("\n There is a user in the survey system with this PPS Number."); 
      return 0; 
     } 
     nodeNum++; 
     temp = temp->next; 
    } 
    printf("\nPPS Number is unique. Continuing...\n We will now ask you for your survey details... "); 

    nodesAdded++; 
    return 1; 

} 
+0

Все ваши 'while (temp-> next ...) ... if (sortedInsert ... break ... temp-> next = newNode' имеет неприятный запах. Повторите логику. –

ответ

0

addElement звонки sortedInsert вставить newNode в отсортированном позицию, но затем он снова вставляет newNode после temp сразу sortedInsert возвращается. Таким образом, узел всегда вставлен сразу после первого узла, и какой бы узел, который он ранее вставил после, все равно будет указывать на него, поэтому список будет циклически без конца.

Ваш код также просачивает память в addElement, если checkUnique не работает, и по этой же причине вставляет узел мусора в addElement_AtStart. Необязательно использовать специальный случай для вставки первого элемента в список и реплицировать весь код, задающий вопросы; это очень плохо. Кроме того, checkUnique изменяет глобальное состояние (nodesAdded), даже если вызывающий код может решить не вставлять узел.

Редактировать: меня уже вызвали в прошлом для предоставления рабочего кода вместо ответа на вопрос. Я считаю, что совет, который я дал выше, устраняет проблему, но есть дополнительные проблемы, которые заставляют его терпеть неудачу. Я создал простой рабочий пример here, поэтому вы можете смотреть на него, только если вы действительно хотите ... Если вы посмотрите на него, внимательно изучите его, чтобы узнать, как устранены особые и дублированные случаи.

+0

вы бы я могу удалить то, что вы подразумеваете под узлом мусора? Я удалил код, который повторно вводит newNode, я верю, но у меня такие же ошибки. – AnthonyGordon

+0

'addElement_AtStart' выделяет новый узел, затем запрашивает pps и если' checkUnique' делает не возвращать 1, он снова вызывает 'addElement_AtStart'.После того, как это возвращается, он все равно вставляет неинициализированный' newNode'. – pat

+0

Я попытался добавить free (temp) в предложение else для проверки уникальности, однако он не предоставил разрешение. Является ли какой-то особый способ нераспределять узел? – AnthonyGordon

Смежные вопросы