简体   繁体   中英

Sorted Link List Recursion

I am trying to sort a random linked list from least to greatest. I have the sorting part down, but my issue is that it's not printing as many random numbers as it should. It should be printing 21 numbers, but I've been getting a nice variety. Any help would be appreciated!

//trouble function
node *sortedInsert(node *head, int data){
    node *temp1, *temp2;
    if(head == NULL)
        head = inserthead(head, data);
    else{
        //Case for if data is less than current node
        if(data <= head->info){
            temp1 = head;
            head = inserthead(head, data);
            head->next = temp1;
        } else {
            if(head->next == NULL)
                head->next == inserthead(head->next, data);
            //Case for if data is greater than current node, but less than next node
            else if(data > head->info && (data <= head->next->info)){
                temp1 = inserthead(temp1, data);
                temp2 = head->next;
                head->next = temp1;
                temp1->next = temp2;
            } else {
                //base case
                sortedInsert(head->next, data);
                }
            }
        }
    return head;
}
//from main, how the function is called:
for(i=0; i<=N; i++){
    sortList = sortedInsert(sortList, rand()%N);
}

at the line

if(head->next == NULL) head->next == inserthead(head->next, data);

you use two equal signs instead of one, so you have a boolean comparison and not an assignment.

with assignment (one equal sign) the code works:

./a.out 0 1 2 3 3 6 6 6 6 7 9 10 11 12 12 13 15 15 16 17 19

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM