0

insertion of node in linked list at beginning and at end

#include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }; struct node * starting_node(int x, struct node *y) { struct node *newnode; newnode = (struct node *)malloc(sizeof(struct node)); newnode -> data = x; newnode -> next = y; printf("hello %d \n", y->data); y = newnode; return y; } struct node * ending_node(int a, struct node *b) { struct node *node_new; node_new = (struct node *)malloc(sizeof(struct node)); b -> next = node_new; b = node_new; node_new -> data = a; node_new -> next = 0; return b; }; int main() { struct node *head, *new_node, *temp; int choice; head = 0; while(choice) { new_node = (struct node *)malloc(sizeof(struct node)); printf("enter the data"); scanf("%d",&(new_node -> data)); new_node -> next = 0; if(head == 0) { head = temp = new_node; } else { temp -> next = new_node; temp = new_node; } printf("do u want to continue (0,1)"); scanf("%d",&choice); } temp = head; while(temp != 0) { printf("%d\n", temp -> data); temp = temp -> next; } int newdata, end_data; printf("enter the data for the beginning node :"); scanf("%d",&newdata); head = starting_node(newdata, head); printf("enter the data for the end node :"); scanf("%d", &end_data); temp = ending_node(end_data, temp); //Now, At last print the final linked list.... temp = head; while(temp != 0) { printf("%d\n", temp -> data); temp = temp -> next; } return 0; } In the above code output is not coming

25th Mar 2020, 1:53 PM
Rishabh Lal Srivastava
Rishabh Lal Srivastava - avatar
1 Resposta
+ 1
When you printing the list at first time (right after input loop) you modifying the "temp" variable. After print loop it will be NULL. Then you use that "temp" variable to add ending node, but it equals NULL (program terminates due to access violation). Use another variable to print list, or, better, declare a function to print it.
25th Mar 2020, 2:18 PM
andriy kan
andriy kan - avatar