C:按升序创建队列

时间:2013-12-05 02:34:28

标签: c dynamic linked-list queue

我正在研究一个问题,即目标是按升序创建链表(队列),而不管它输入的顺序如何。我已经能够构建我的赋值,以便它输入数据并将其推送到堆栈并正确弹出队列中的第一个项目(这是下面的代码)但我似乎无法获得一个有效的算法来构建队列升序。

我通过在addItem中使用第二个函数来重写我的算法,以找到任何新添加的结构的正确位置,以便它现在正确处理排序。我的返工代码如下。

void addItemToQueue(int *identification, float *houlyrate) {
    struct Employee *locateInsertionPoint(int *);
    struct Employee *newAddress, *here;

    newAddress = (struct Employee *) malloc(sizeof(struct Employee));   // Allocate Space for the new structure
    if (newAddress == (struct Employee *) NULL) {                       // Display Error message and terminate if allocation fails
        printf("\nERROR: Failed to allocate memory for this structure.\n");
        free(queueOut);                                                 // Free the Queue in the event memory fails to allocate new space
        exit(1);
    }

    if (queueOut == NULL) {                                             // Does queue exist
        newAddress->nextAddress = NULL;
        queueOut = newAddress;
    }
    else if (*identification < queueOut->idnum) {                       // Is the new ID Number less than the old ID Number
        newAddress->nextAddress = queueOut;
        queueOut = newAddress;
    }
    else {
        here = locateInsertionPoint(identification);                    // Use locateInsertionPoint() function to find proper place for new ID
        newAddress->nextAddress = here->nextAddress;
        here->nextAddress = newAddress;
    }
    newAddress->idnum = *identification;                                // Make new structure id num equal to the passed id num
    newAddress->hourlyrate = *houlyrate;                                // Make new structure payrate equal to the passed payrate
}


struct Employee *locateInsertionPoint (int *idnum) {
    struct Employee *one, *two;
    one = queueOut;
    two = one->nextAddress;
    if (two == NULL) {                                                  // Check if There is only 1 item
        return one;
    }
    while (1) {                                                         // LOOP
        if (*idnum < two->idnum) {                                      // Is the new ID less than current ID
            break;
        }
        else if (two->nextAddress == NULL) {                            // IF Not, is the next address NULL
            one = two;
            break;
        }
        else {                                                          // IF Not, shift pointers to read next set
            one = two;
            two = one->nextAddress;
        }
    }
    return one;
}

1 个答案:

答案 0 :(得分:1)

看起来您正在尝试实施插入排序以保持队列排序。如果是这种情况,那么您的实施中会遇到一些问题。您没有正确维护列表。当您找到要将项目插入列表的点时,除了将新元素设置为指向当前元素之外,还需要更新前一元素的next指针以指向新元素

我建议您查看一些链接列表示例,例如如何插入链接列表。链接列表是一个完整的基本数据结构,值得花时间进行全面的理解。