c - 从数组插入链表节点,但并非所有节点都被插入

标签 c arrays linked-list

我有以下双向链表结构:

struct coords
{
    int x;
    int y;
    struct coords* previous;
    struct coords* next;
};

我有一个包含以下值的链接列表,此处显示为(x,y):

head                                                          tail
(-1, -1) <--> (0, 1) <--> (2, 1) <--> (1, 0) <--> (0, 2) <--> (-1, -1)

根据我的实现,头部和尾部始终为(-1,-1)。我还有 newCoords,一个大小为 4 的 coords* 数组,其中包含以下元素:

[(0, 2), (2, 2), (1, 3), no value]

newCoords 可以具有零到四个指定元素。我还跟踪名为 newCoords 的 int 中的节点数(当前值为 3)。我想将这些节点添加到我的链表中,位于尾部和最后一个非尾部节点之间。为此,我有以下代码(为了清楚起见,删除了打印语句):

void insert (struct coords* position, struct coords* newCoord)
    {
        newCoord->next = position->next;
        newCoord->previous = position;
        position->next = newCoord;
    }
... //here I create the initial linked list
struct coords* newCoords[4]; //4 is the maximum number of new coords that can be added
int numberOfNewCoords = 0;
... //here I fill newCoords, and as I do I increment numberOfNewCoords by 1
if (numberOfNewCoords > 0) //numberOfNewCoords stores the number of coords in newCoords
    {
        struct coords* temp = tail->previous;
        /* add new possible locations to list */
        for (int i = 0; i < numberOfNewCoords; i++)
            {
                insert(temp, newCoords[i]);
                temp = temp->next;
            }
     }

newCoords 中的前两个值按照我的预期添加。但是,最后一个值不会插入到链表中。插入到应该插入的位置的是一个节点,其数字在每次运行程序时都会发生变化。该列表应该是

head                                                                                              tail
(-1, -1) <--> (0, 1) <--> (2, 1) <--> (1, 0) <--> (0, 2) <--> (0, 2) <--> (2, 2) <--> (1, 3) <--> (-1, -1)

但相反

head                                                                                                          tail
(-1, -1) <--> (0, 1) <--> (2, 1) <--> (1, 0) <--> (0, 2) <--> (0, 2) <--> (2, 2) <--> (9765060, 9770824) <--> (-1, -1)

最佳答案

澄清一下,您确定使用了 malloc 来分配内存吗?

关于c - 从数组插入链表节点,但并非所有节点都被插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17207168/

相关文章:

C malloc struct 抛出内存冲突异常(准系统示例)

php - MYSQL/PHP 两个多选下拉过滤器(PDO)

c++ - 为什么我对 pointer->next == NULL 的检查在我的链表中出现错误?

java - JNI : equivalent of uint *vboIds in Java

数字的累积和

php - 如何按值删除重复的数组元素并保留最新条目?

java - 如何找到不同的流派然后添加到数组链表中

c++ - 链表函数有问题

使用 ASCII 将小写字母转换为大写字母

arrays - 如何在 MongoDB 的数组中查找所有内容