Linked List SortedInsert()函数

时间:2016-08-09 03:43:59

标签: c linked-list

我使用C编写了一个SortedInsert()函数来将新节点插入到按递增顺序排序的给定列表中。我的SortedInsert()函数代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>


struct node
{
    int data;
    struct node *next;
};

void push(struct node** head, int data_new) {
    struct node* headNode;
    headNode = (node*)malloc(sizeof(struct node));
    headNode->data = data_new;
    headNode->next = *head;
    *head = headNode;
}

struct node* BuildFunny() {
    struct node*head = NULL;
    push(&head, 2);
    push(&head->next, 3);
    push(&head->next->next, 8);
    push(&head->next->next->next, 10);
    push(&head->next->next->next->next, 15);
    head->next->next->next->next->next = NULL;

    return head;
}

void SortedInsert(struct node** headRef, struct node* newNode){
    if (*headRef == NULL || (*headRef)->data >= newNode->data){
        newNode->next = *headRef;
        *headRef = newNode;
    }
    else {
        struct node* current;
        current = *headRef;
        while (current->next->data <= newNode->data && current->next != NULL){
            current = current->next;
        }
        newNode->next = current->next;
        current->next = newNode;
    }
}

主要功能是:

int main()
{
    struct node* head;
    head = BuildFunny();
    struct node* newNode = (struct node*)malloc(sizeof(struct node));
    newNode->data = 1;
    newNode->next = NULL;
    SortedInsert(&head, newNode);

    struct node* newNode1 = (struct node*)malloc(sizeof(struct node));
    newNode1->data = 6;
    newNode1->next = NULL;
    SortedInsert(&head, newNode1);

    /*
    struct node* newNode2 = (struct node*)malloc(sizeof(struct node));
    newNode2->data = 20;
    newNode2->next = NULL;
    SortedInsert(&head, newNode2);
    */

    while(head != NULL){
        printf("%d ", head->data);
        head = head->next;
    }


    return 0;
}

问题是我能正确地将数字1和6插入到列表中,但是数字20总是给我错误(取消注释newNode2会给出错误)。我不知道为什么我不能将超过15的号码插入我的列表中。有人可以帮助我制作超过15的数字也可以插入列表的末尾吗?

1 个答案:

答案 0 :(得分:1)

这个问题可能是问题

while (current->next->data <= newNode->data && current->next != NULL)

将其更改为

前检查NULL
while (current->next != NULL && (current->next->data <= newNode->data))

使用您的代码,当current->nextNULL时,它会尝试第一个引用NULL指针导致问题的条件。 因此,当在列表中添加比现有数字更多的数字时,您将遇到问题。