All I am trying to do is to create a link list which takes number that may not possibly be in order. For example, I try to read a file which says,
101
102
105
104
103
101 <-------- Duplication
It should create a linked list with ascending order. I wrote a but it gives me a segmentation fault and after spending many hours deskchecking the code, I couldnt find the bug. Can anyone help me out?
CODE BELOW
NB: this is just part of the code, but the error lies in the function addBlock().
Expand|Select|Wrap|Line Numbers
- struct block
- {
- struct block *down;
- int number;
- };
- typedef struct block block;
- void addBlock(block **start, int number);
- int main(int argc, char *argv[])
- {
- block *head = NULL;
- /* Codes to read every line of a file and obtain the number and store in number variable below, goes through a loop
- to do this and loop goes on until the end of file is reach */
- int number = some Function that Reads Number Into It ;
- add(Block(&head, nuumber);
- }
- void addBlock(block **start, int number)
- {
- /*
- There are 4 possibilities here:
- 1) temp is the first block
- 2) temp can fit between 2 blocks,
- 3) A block with same number already exists
- 4) None of the above, set temp to the end of list
- */
- block *temp = newBlock(number);
- block *curr = NULL; /*curr scans every element in the link list*/
- if(*start == NULL) /*First block*/
- {
- *start = temp;
- }
- else if ((*start)->down == NULL) /*Second block*/
- {
- /*Check whether temp can go as first block*/
- if(temp->number < (*start)->number)
- {
- temp->down = *start;
- *start = temp;
- }
- else /*Put it to the end of the list, as second element*/
- (*start)->down = temp;
- }
- else /*If there is more than 2 blocks*/
- {
- /*Scan down the list*/
- for(curr = *start; curr->down != NULL; curr = curr->down)
- {
- /*Check if temp can fit in betwen any blocks*/
- if(curr->number < temp->number &&
- curr->down->number > temp->number)
- {
- temp->down = curr->down;
- curr->down = temp;
- break;
- }
- }
- }
- /*Checks if the new block has been added or not, if not
- it will be added to the end of the list */
- if(temp->down == NULL)
- curr->down = temp;
- }