c - Segmentation fault -
adds node ascending ordered linked list
i have seen similar stuff here didnt me. please correct me wherever wrong.
#include<stdio.h> #include<stdlib.h> struct node { int data; struct node* link; }; struct node* head = null; void add(int); void print(); int main() { add(1); print(); add(2); print(); add(5); print(); add(4); print(); add(3); print(); return 0; } ***/* if list empty or if new node inserted before first node*/*** void add( int num) { struct node* temp; temp = head; struct node* newnode = (struct node*)malloc(sizeof(struct node)); newnode->data = num; newnode->link = null; if((head == null)||( head->data > num)) { newnode->link = head; head = newnode; } else { ***/* traverse entire linked list search position insert new node*/*** while(temp!=null) { if(temp->data <= num && ( temp->link->data > num || temp->link == null)) { newnode->link = temp->link; temp->link = newnode; return; } temp= temp->link; } } } ***/*display content of linked list*/*** void print() { struct node* temp; temp = head; while(temp!=null) { printf("%d", temp->data); temp=temp->link; } printf("\n"); }
while running code o/p :
1
segmentation fault (core dumped)
please me, how solve problem
the culprit line:
if(temp->data <= num && ( temp->link->data > num || temp->link == null))
you not checking temp->link
not null
before evaluating it. change to:
if(temp->data <= num && ( temp->link == null || temp->link->data > num))
to make safe taking advantage of short-circuit evaluation.
Comments
Post a Comment