2014-12-10 3 views
3
#include <stdio.h> 
#include <conio.h> 

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

int main() { 
    struct node* head = NULL; 
    struct node* second = NULL; 
    struct node* third = NULL; 

    head = (struct node*)malloc(sizeof(struct node)); 
    second = (struct node*)malloc(sizeof(struct node)); 
    third = (struct node*)malloc(sizeof(struct node)); 

    head->data = 1; 
    head->next = second; 

    second->data = 2; 
    second->next = third; 

    third->data = 3; 
    third->next = NULL; 

    struct node* temp; 
    temp = head; 

    while (temp != NULL) { // for printing the linked list 
    printf("%d ",temp->data); 
    temp = temp->next; 
    } 

    struct node* new1; 
    struct node* temp1; 

    temp1 = head; 

    while (temp1 != NULL) { // for traversing to the end 
    temp1 = temp1->next; 
    } 

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

    new1->data = 5; 
    new1->next = NULL; 

    temp1->next = new1; 

    while (temp1 != NULL) { // again for printing the list 
    printf("%d ",temp1->data); 
    temp1 = temp1->next; 
    } 

    return 0; 
} 

Я пытаюсь вставить узел в конец связанного списка, но он не работает. Я создал связанный список успешно, но я не могу вставить узел в конец. Это то, чему меня учил мой учитель, но он не работает.Вставка узла в конец связанного списка

+1

Что именно «не работает»? – Codor

+0

После цикла 'while (temp1! = NULL)' 'temp1' будет' NULL', чтобы вы не могли его разыменовать. – interjay

+1

Не бросайте 'malloc' в C. – crashmstr

ответ

2

В моем понимании, в той части, которая комментируется

// for traversing to the end 

итерации реализации слишком далеко; условие должно быть

while (temp1->next != NULL) 

прекратить, как только последний узел будет достигнут, если не прекращение NULL указателя достигается.

+0

его работающий сейчас, но все же я получаю этот вывод - 1 2 3 3 5; вместо этого правый выход должен быть 1 2 3 1 2 3 5; ? –

2
while(temp1 != NULL)   // for traversing to the end 
{ 
    temp1 = temp1->next; 
} 

Это будет цикл до тех пор, пока temp1являетсяNULL. Вам нужно получить последний узел, т. Е. Когда temp1->next равен NULL, т.е.

while(temp1->next != NULL)   // for traversing to the end 
{ 
    temp1 = temp1->next; 
} 
Смежные вопросы