插入已排序的链接列表

时间:2015-04-05 05:40:36

标签: c linked-list

尝试编写一个要求用户输入整数的函数,然后按升序将其插入到链表中。

typedef struct _listnode{
    int item;
    struct _listnode *next;
} ListNode;         

typedef struct _linkedlist{
    int size;
    ListNode *head;
} LinkedList;           

void insertSortedLinkedList(LinkedList *l)
{
    ListNode *cur;
    int x;
    printf("please input an integer you want to add to the linked list:");
    scanf("%d", &x);

    if (l->head == NULL) // linkedlist is empty, inserting as first element
    {
        l->head = malloc(sizeof(ListNode));
        l->head->item = x;
        l->head->next = NULL;
    }
    else
    {
        cur = l->head;
        if (x < cur->item) // data is smaller than first element, we will insert at first element and update head.
        {
            cur->next->item = cur->item; // store current element as next element.
            cur->item = x;
            cur->next = cur->next->next;
        }
    }
    l->size++;
}

该功能尚未完成,但如果数据小于第一个元素,为什么我的代码无效?

2 个答案:

答案 0 :(得分:1)

插入函数的else分支假定cur->next不是NULL(因为您将值设置为cur->next->item)。现在想象插入两个数字(第二个比第一个小)。在第一次插入时,l->head->next设置为NULL。因此,在第二次插入时,程序将在尝试将cur->next->item设置为某个值时崩溃。您应该创建一个节点(即通过malloc()分配内存),初始化节点以根据需要包含字段,然后将其设置为cur->next

答案 1 :(得分:1)

首先,您需要为新元素创建节点,如下所示:

ListNode* newNode =  malloc(sizeof(ListNode));
newNode ->item = x;

现在更改您的代码:

if (x < l->head->item) // data is smaller than first element, we will insert at first element and update head.
    {
        newNode->next = l->head;
        l->head = newNode;
    }
}

就像你说的那样,代码不完整是,并通过列表循环,直到找到插入新节点的正确位置。

可以编写1个代码来处理所有情况。 处理这些情况的一种常见方法是将节点放在链接列表的头部。

相关问题