链接列表功能在c中排序

时间:2016-10-31 13:19:57

标签: c linked-list

我想编辑insertSortedLL链表功能

插入代码后,我打印出的链表似乎相反,例如输出:5 4 3 2 1 我希望输出打印1 2 3 4 5 基本上问题是如何对链表值进行排序

int insertSortedLL(LinkedList *ll, int item)
{
  insertNode(ll, 0,item);
  printList(ll);
}

void printList(LinkedList *ll) {

ListNode *cur;
if (ll == NULL)
    return;
cur = ll->head;

if (cur == NULL)
    printf("Empty");
while (cur != NULL)
{
    printf("%d ", cur->item);
    cur = cur->next;
}
printf("\n");
}

void removeAllItems(LinkedList *ll)
{
ListNode *cur = ll->head;
ListNode *tmp;

while (cur != NULL) {
    tmp = cur->next;
    free(cur);
    cur = tmp;
}
ll->head = NULL;
ll->size = 0;
}

ListNode * findNode(LinkedList *ll, int index) {

ListNode *temp;

if (ll == NULL || index < 0 || index >= ll->size)
    return NULL;

temp = ll->head;

if (temp == NULL || index < 0)
    return NULL;

while (index > 0) {
    temp = temp->next;
    if (temp == NULL)
        return NULL;
    index--;
}

return temp;
}

int insertNode(LinkedList *ll, int index, int value) {

ListNode *pre, *cur;

if (ll == NULL || index < 0 || index > ll->size + 1)
    return -1;

// If empty list or inserting first node, need to update head pointer
if (ll->head == NULL || index == 0) {
    cur = ll->head;
    ll->head = malloc(sizeof(ListNode));
    ll->head->item = value;
    ll->head->next = cur;
    ll->size++;
    return 0;
}

// Find the nodes before and at the target position
// Create a new node and reconnect the links
if ((pre = findNode(ll, index - 1)) != NULL) {
    cur = pre->next;
    pre->next = malloc(sizeof(ListNode));
    pre->next->item = value;
    pre->next->next = cur;
    ll->size++;
    return 0;
}

return -1;
}

int removeNode(LinkedList *ll, int index) {

ListNode *pre, *cur;

// Highest index we can remove is size-1
if (ll == NULL || index < 0 || index >= ll->size)
    return -1;

// If removing first node, need to update head pointer
if (index == 0) {
    cur = ll->head->next;
    free(ll->head);
    ll->head = cur;
    ll->size--;

    return 0;
}

// Find the nodes before and after the target position
// Free the target node and reconnect the links
if ((pre = findNode(ll, index - 1)) != NULL) {

    if (pre->next == NULL)
        return -1;

    cur = pre->next;
    pre->next = cur->next;
    free(cur);
    ll->size--;
    return 0;
}

return -1;
}

1 个答案:

答案 0 :(得分:0)

insertSortedLL()函数应将节点插入到正确位置的排序列表中。如果使用此函数构建列表,则将对结果列表进行排序。

您的insertSortedLL()函数需要遍历列表,将每个节点的item与您要插入的item进行比较。该项目将插入第一个节点的位置,该位置包含大于插入值的值,或者在列表的末尾。以下是如何编写此代码的示例:

int insertSortedLL(LinkedList *ll, int item)
{
    ListNode *cur = ll->head;
    int ll_size = ll->size;
    int i;

    for (i = 0; i <= ll_size; i++) {
        if ((ll_size - i) == 0 || item < cur->item) {
            insertNode(ll, i, item);
            return 0;
        }
        cur = cur->next;
    }

    return -1;
}