Using insertion sort on a singly linked list

前端 未结 7 1004
春和景丽
春和景丽 2021-02-06 10:11

So I have an assignment where I\'m giving a random list of number and I need to sort them using insertion sort. I must use a singly linked list. I looked around at other posts b

7条回答
  •  梦如初夏
    2021-02-06 11:08

    struct node {
        int data;
        struct node *next;
    };
    
    
    void insertion(struct node **head) {
        if((*head)== NULL || (*head)->next == NULL) {
           return;
        }
        struct node *t1 = (*head)->next;
        while(t1 != NULL) {
            int sec_data = t1->data;
            int found = 0;
            struct node *t2 = *head;
            while(t2 != t1) {
                if(t2->data > t1->data && found == 0) {
                    sec_data = t2->data;
                    t2->data = t1->data;
                    found = 1;
                    t2 = t2->next;
                } else {
                    if(found == 1) {
                        int temp = sec_data;
                        sec_data = t2->data;
                        t2->data = temp;
                    }
                    t2 = t2->next;
                }
           }
           t2->data = sec_data;
           t1 = t1->next;
        }
    }
    

提交回复
热议问题