将节点添加到链表中的随机点

时间:2018-09-23 18:47:09

标签: c pointers linked-list nodes

因此,我有一个将节点添加到链表的功能,而不仅仅是在链表的末尾添加元素,我试图从用户要添加的位置获取用户输入。然后,需要添加它并转移其他所有内容而不删除其他任何内容。我对此很麻烦。

下面我将展示我的代码,虽然有点混乱,但我会尽力解释。

void InsertGraphicElement(struct RasterGraphic *pA) {
    int counter = 1;
    int response = 0;
    char tempString[256];
    struct GraphicElement *newNode = malloc(sizeof(*newNode));
    if (newNode == NULL)
        return;

    newNode->fileName = malloc(256 * sizeof(char));
    if (newNode->fileName == NULL)
        return;
    newNode->pNext = NULL;

    printf("Insert a GraphicElement in the RasterGraphic\nPlease enter the GraphicElement filename: ");
    scanf("%s", newNode->fileName);

    if (pA->GraphicElements == NULL) {
        pA->GraphicElements = newNode;
        printf("This is the first GraphicElement in the list\n");
    } else {
        struct GraphicElement *tempHead = pA->GraphicElements;
        struct GraphicElement *tempTail = pA->GraphicElements;
        while (tempHead->pNext != NULL) {
            tempHead = tempHead->pNext;
            counter++;
        }
        tempHead->pNext = newNode;

        printf("There are %d GraphicElement(s) in the list. Please specify the position (<= %d) to insert at :", counter, counter);
        scanf("%d", &response);

        if (response == counter) {
            return;
        } else {
            while (response < counter) {
                tempTail = tempTail->pNext;
                response++;
            }       
        }
    }
    return;
}

这是不完整的,我一直在弄乱试图找出它的代码,但是如您所见,我可以毫无问题地添加到列表的末尾。我遇到的麻烦是,如果列表1,2,3,4,,5中有5个元素,而我添加了第六个元素,则列表显然看起来像这样的1,2,3,4,5,6。我想做的是接受用户输入,例如他们想将第六个元素添加到可能的位置3,因此列表看起来像这样1,2,6,3,4,5。香港专业教育学院尝试了一堆东西,朝着正确的方向,否则将不胜感激。谢谢

下面是我的结构定义

struct GraphicElement {
    char *fileName;
    struct GraphicElement *pNext;
};
struct RasterGraphic {
    //int numNodes;
    struct GraphicElement *GraphicElements;
};

1 个答案:

答案 0 :(得分:0)

您当前具有以下条件:

if (response == counter) {
    return;
}
else {
    while(response < counter){
        tempTail = tempTail->pNext;
        response++;
    }
}       

我将其修改为:

if (response > counter+1 || response < 1) { // These are all invalid values
    return;
}
else if (response == 1) { // We are replacing the head node
    newNode->pNext = tempTail->pNext;
    pA->GraphicElements = newNode;
}
else {
    while(response-- > 2) { // Responses are 1-indexed
        tempTail = tempTail->pNext;
    }
    newNode->pNext = tempTail->pNext; // IMPORTANT: Update newNode reference FIRST
    tempTail->pNext = newNode; // Update tempTail to point to newNode
}  

免责声明-未经任何测试

我试图评论我认为很重要的事情。不过,这里要记住的关键是,为了在单链列表中插入内容,必须先更新新节点以指向链表的其余部分,然后再更新之前的节点的引用,否则列表的最后一位将永远丢失,并且您将循环引用最后一个节点。

作为旁注,您每次要向其添加新元素时,似乎遍历整个链表两次。我可能建议对每次添加链表时要更新的链表中有多少项进行滚动计数,以免在效率很重要时重新计算此值的开销。

希望这会有所帮助!

编辑:您必须删除将新节点添加到函数顶部的列表末尾的行,此功能才能起作用。 “ tempHead-> pNext = newNode;”

相关问题