2015-03-09 2 views
-1

Как исправить ошибку, которую я получаю при запуске программы? Im пытается сделать головную точку на адрес первого, а затем сможет передать * сначала через функцию, в которой будет создан новый узел, пользователь может предоставить ему данные во время выполнения, а затем сначала укажет на новый узел ! Правильно ли я это делаю?C связанный список и узловая программа, почему я получаю исключение?

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

void addToStart (struct node** head); 
void Menu(); 
void DisplayList(struct node* head); 

struct node{ 

    int data; 
    struct node *next; 

}; 


void main(){ 

    int option = 0; 

    struct node *head; 
    struct node *first; 
    head = (struct node*)malloc(sizeof(struct node)); 
    first = (struct node*)malloc(sizeof(struct node)); 

    head->data= 0; 
    head->next = first; 
    first->data = 1; 
    first->next = NULL; 

    Menu(); 
    scanf(" %d", option); 

    while(option != 6){ 
     switch(option){ 
     case 1: 
      addToStart(&first); 
      break; 
     case 3: 
      DisplayList(head); 
     break; 
    case 6: 
     exit(0); 
     break; 

    default: 
     printf("\nTry Again"); 
     break; 
     }//switch end 
    }//while end 

} 

void addToStart (struct node** first) 
{ 
struct node *newNode; 
newNode = (struct node*)malloc(sizeof(struct node)); 
printf("\nEnter data for this node"); 
scanf("%d", &newNode->data); 
newNode->next = *first; 
*first = newNode; // transfer the address of newNode' to 'head' 
} 

void Menu(){ 

    printf("1) Add a node.\n"); 
    printf("3) Display all nodes.\n"); 
    printf("6) Exit.\n"); 


} 

void DisplayList(struct node* head){ 

    struct node *temp; 
    temp =(struct node*)malloc(sizeof(struct node)); 
    temp = head; 
    while(temp!= NULL) 
    { 
     printf("Data: %d", temp->data); // show the data 
     temp = temp->next; 
    } 
} 
+0

где и какие ошибки, пожалуйста? –

+1

'temp = (struct node *) malloc (sizeof (struct node)); temp = head; 'Это, вероятно, не связано с вашей ошибкой, но если вы устанавливаете' temp' 'head', то первая строка не нужна и приводит к утечке памяти. –

+0

и 'addToStart (& first);' -> 'addToStart (&head);'?, 'While (option! = 6) {': never update 'option' – BLUEPIXY

ответ

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


struct node{ 

    int data; 
    struct node *next; 

}; 

void addToStart (struct node** head); 
void Menu(); 
void DisplayList(struct node* head); 




int main(){ 

    int option = 0; 

    struct node *head; 
    //struct node *first; 
    //head = (struct node*)malloc(sizeof(struct node)); 
    //first = (struct node*)malloc(sizeof(struct node)); 

    head = NULL; 

    option = 0; 
    while(option != 6){ 
     Menu(); 
     scanf(" %d", &option); 
     switch(option){ 

      case 1: 
       addToStart(&head); 
           break; 
      case 3: 
       DisplayList(head); 
           break; 
      case 6: 
       exit(0); 

       break; 

      default: 
       printf("\nTry Again"); 
       break; 
     }//switch end 
    }//while end 

} 

void addToStart (struct node** head) 
{ 
    struct node *newNode; 
    newNode = (struct node*)malloc(sizeof(struct node)); 
    printf("\nEnter data for this node"); 
    scanf("%d", &newNode->data); 
    newNode->next = NULL; 
    if (*head==NULL) 
    { 
     *head = newNode; 
    } 
    else 
    { 
     struct node *lastNode = *head; 
     while(lastNode->next!=NULL) 
      lastNode = lastNode->next; 
     lastNode->next = newNode; 


    } 

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

void Menu(){ 

    printf("\n1) Add a node.\n"); 
    printf("3) Display all nodes.\n"); 
    printf("6) Exit.\n"); 


} 

void DisplayList(struct node* head){ 

    struct node *temp; 
    temp =(struct node*)malloc(sizeof(struct node)); 
    temp = head; 
    while(temp!= NULL) 
    { 
     printf("Data: %d", temp->data); // show the data 
     temp = temp->next; 
    } 
} 

Это работает.

Много очков вы должны рассмотреть следующие вопросы:

1) она int main, не void main()

2) дают адрес переменной, которую вы хотите установить значение, когда вы делаете scanf. это должно быть scanf(" %d", &option); не scanf(" %d", option);

3) Когда вы создали новый узел, вы не устанавливали его рядом с NULL. Это отсутствовало. newNode->next = NULL;

4) Вы были в бесконечном цикле. option не обновлялся. Я добавил это. Кроме того, меню должно отображаться после того, как пользователь дал свой выбор.

5) Проверка распределения памяти отсутствует. Что делать, если malloc возвращает NULL?

6) Вы путались с first и head. Конвенция должна использовать head.

7) Я бы использовал typedef, а не struct node каждый раз. Это остается как упражнение :)

ОП, этот список не является исчерпывающим.

Если вы хотите, чтобы отобразить числа в обратном порядке, изменить еще часть в addToStart как этот

else 
    { 
     newNode->next = *head; 
     *head = newNode; 
    } 
+0

3):' next' был установлен. – BLUEPIXY

+0

Ваш 'addToStart' -' addToLast'. – BLUEPIXY

+0

@BLUEPIXY, да. Не понял. Я думаю, что это хорошо, так как ясно, что OP все еще изучает основы. Я дал addToLast, OP должен уметь вычислять addToStart. – Anon

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


struct node{ 

    int data; 
    struct node *next; 

}; 

void addToStart (struct node** head); 
void addToEnd (struct node** head); 
void Menu(); 
void Size(struct node* head); 
void DisplayList(struct node* head); 
void SearchList(struct node* head); 



int main(){ 

    int option = 0; 

    struct node *head; 
    struct node *first; 
    head = (struct node*)malloc(sizeof(struct node)); 
    first = (struct node*)malloc(sizeof(struct node)); 

    head = NULL; 

    option = 0; 
    while(option != 6){ 
     Menu(); 
     scanf(" %d", &option); 
     switch(option){ 

      case 1: 
       addToStart(&head); 
           break; 
      case 2: 
       addToEnd(&head); 
       break; 
      case 3: 
       DisplayList(head); 
           break; 
      case 4: 
       Size(head); 
       break; 
      case 5: 
       SearchList(head); 
       break; 
      case 6: 
       free(head); 
       free(first); 
       exit(0); 
       break; 

      default: 
       printf("\nTry Again"); 
       break; 
     }//switch end 
    }//while end 

} 

void addToStart (struct node** head) 
{ 
    struct node *newNode; 
    newNode = (struct node*)malloc(sizeof(struct node)); 
    printf("\nEnter data for this node:\n"); 
    scanf("%d", &newNode->data); 
    newNode->next = NULL; 
    if (*head==NULL) 
    { 
     *head = newNode; 
    } 
    else 
    { 
     newNode->next = *head; 
     *head = newNode; 

    } 
    printf("%u,%u",&head,&newNode); 
    // *first = newNode; // transfer the address of newNode' to 'head' 
} 

void addToEnd (struct node** head) 
{ 
    struct node *newNode; 
    newNode = (struct node*)malloc(sizeof(struct node)); 
    printf("\nEnter data for this node:\n"); 
    scanf("%d", &newNode->data); 
    newNode->next = NULL; 
    if (*head==NULL) 
    { 
     *head = newNode; 
    } 
    else 
    { 
     struct node *lastNode = *head; 
     while(lastNode->next != NULL){ 
       lastNode = lastNode->next; 
      lastNode->next = newNode; 
     } 

     *head = newNode; 

    } 

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

void Size(struct node* head) 
    { 
     int len = 0; 

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

     while(temp != NULL) 
     { 
      len++; 
      temp = temp->next; 

     } 
     printf("Size of list: %d", len); 
    } 


void Menu(){ 

    printf("\n1) Add a node.\n"); 
    printf("2) Add node to end.\n"); 
    printf("3) Display all nodes.\n"); 
    printf("4) Display the length of list.\n"); 
    printf("5) Search the list.\n"); 
    printf("6) Exit.\n"); 


} 

void DisplayList(struct node* head){ 

    struct node *temp; 
    temp =(struct node*)malloc(sizeof(struct node)); 
    temp = head; 
    while(temp!= NULL) 
    { 
     printf("Data: %d ", temp->data); // show the data 
     temp = temp->next; 
    } 
} 



void SearchList(struct node* head){ 

    int keynum; 
    struct node *temp; 
    temp =(struct node*)malloc(sizeof(struct node)); 
    temp = head; 

    printf("\nEnter number:\n"); 
    scanf(" %d", &keynum); 

    if(temp->data == keynum){ 
     printf("\n%d was found in the list!\n", keynum); 
    } 
    else{ 
     printf("\n%d is not in the list!\n", keynum); 

    } 
} 
+0

Поздравляю, это выглядит аккуратно и аккуратно :). Я вижу, что вы добавили новые методы самостоятельно. – Anon

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