Inserting a node at the end of a linked list
#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;
}
I'm trying to insert a node at the end of my linked list, but it doesn't work. I created the linked list successfully, but I cannot insert a node at the end. My teacher taught me this, but it doesn't work.
+3
source to share
2 answers