linked list - segmenation fault error in my linkedList -C -
i put few pieces of code make linked list adds head(has special function) , in middle(also special function). problem is, need provide program numbers , insert them nodes in linkedlist. however, display function(to display tree of nodes) gives segmentation fault , taking values in without display function. i'm new malloc suspect problem there? thanks
#include<stdio.h> #include<stdlib.h> /*linkedlist struct*/ struct node { int data; struct node *next; }; /*inserting head-node*/ struct node *insert_head(struct node *head, int number) { struct node *temp; temp = malloc(sizeof(struct node)); if(temp == null) { printf("not enough memory\n"); exit(1); } temp->data = number; temp->next = head; head = temp; return head; } /*inserting inside list*/ void after_me(struct node *me, int number) { struct node *temp; temp = malloc(sizeof(struct node)); if(temp == null) { printf("not enough memory\n"); exit(1); } temp->data = number; temp->next = me->next; me->next = temp; } /*printing list*/ void display(struct node *head) { struct node *moving_ptr = head; while(moving_ptr != null) { printf("%d-->",moving_ptr->data); moving_ptr = moving_ptr->next; } } int main() { int index; struct node *head; struct node *previous_node; scanf("%d", &index); while(index > 0) { /*allocating in list */ if(head == null) head = insert_head(head,index); else if((head != null) && (index <= (head->data))) { struct node *temp; head->next = temp; temp->next = head;/*try insert head func.*/ } else if((head != null) && (index > (head->data))) { previous_node->data = index-1; after_me(previous_node,index); } scanf("%d", &index); } display(head); }
i suggest follows.
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next; }; //aggregated 1 place struct node *new_node(int number){ struct node *temp; if(null == (temp = malloc(sizeof(*temp)))){ printf("\nnot enough memory\n"); exit(1); } temp->data = number; temp->next = null; return temp; } struct node *insert_head(struct node *head, int number) { struct node *temp = new_node(number); temp->next = head; return temp; } void after_me(struct node *me, int number){ struct node *temp = new_node(number); temp->next = me->next; me->next = temp; } void display(struct node *head){ struct node *moving_ptr = head; while(moving_ptr != null){ printf("%d", moving_ptr->data); if(moving_ptr = moving_ptr->next) printf("-->"); } putchar('\n'); } struct node *insert(struct node *me, int number){ if(me){ if(number <= me->data){ me = insert_head(me, number); } else { me->next = insert(me->next, number); } } else { me = new_node(number); } return me; } void release(struct node *list){//of course, able replace simple loop(e.g while-loop). if(list){ release(list->next); free(list); } } int main(void){ struct node *head = null; int index; while(1==scanf("%d", &index) && index > 0){ head = insert(head, index); } display(head); release(head); return 0; }
Comments
Post a Comment