Insertion sort @ linked list

I am trying to use this code but the problem is that it hangs and i cant tell why. Any ideas?
It should be an insertion sort using a linked list. Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#include <iostream>
//using namespace std;


struct lnode {
 char *str;
 struct lnode *next;
};

struct lnode *insert(char *data, struct lnode *list);
void free_list(struct lnode *list);
void print_list(struct lnode *list);

int main() {
 char line[1024];
 struct lnode *list;
// cout << "1"<<endl;

 list = NULL;
 while((fgets(line, 1024, stdin)) != NULL) 
  list = insert(line, list);
//  cout << "2"<<endl;
 print_list(list);
 free_list(list);
 return 0;
}

struct lnode *insert(char *data, struct lnode *list) {
 struct lnode *p;
 struct lnode *q;

 /* create a new node */
 p = (struct lnode *)malloc(sizeof(struct lnode));
 /* save data into new node */
 p->str = strdup(data);

 /* first, we handle the case where `data' should be the first element */
 if(list == NULL || strcmp(list->str, data) > 0) {
  /* apperently this !IS! the first element */
  /* now data should [be|becomes] the first element */
  p->next = list;
  return p;
 } else {  
  /* search the linked list for the right location */
  q = list;
  while(q->next != NULL && strcmp(q->next->str, data) < 0) {
   q = q->next;
  }
  p->next = q->next;
  q->next = p;
  return list;
 }
}
    
void free_list(struct lnode *list) {
 struct lnode *p;

 while(list != NULL) {
  p = list->next;
  free(list);
  list = p;
 }
}
  
void print_list(struct lnode *list) {
 struct lnode *p;
  
 for(p = list; p != NULL; p = p->next)
  printf("%s", p->str);
}
line 42 will crash strcmp(list->str, data) will be executed when list is NULL.
!Thanks
What should be changed? If i comment one of the two conditions in the if statement it does not work and if i comment the whole if then there`s the else part that needs to be adressed.
The gamut of changes you can make to code is not limited to commenting stuff out.

if(list == NULL || (list != NULL && strcmp(list->str, data) > 0)) {
scratch that strcmp. There's nothing to compare:
1
2
3
4
5
6
 if(list == NULL || strcmp(list->str, data) > 0) {
  /* apperently this !IS! the first element */
  /* now data should [be|becomes] the first element */
  p->next = list;
  list = p; // Note! Otherwise you'll never see an element in your list
  return p;


After line 39: p->next = NULL; Note: set all pointers to something valid/NULL, otherwise you will constantly get into trouble
Topic archived. No new replies allowed.