C - 代码表示头未声明 - 尝试将节点插入链表

标签 c pointers linked-list singly-linked-list

有人能指出我正确的方向吗?错误显示 head在此行中未声明:newNode1 -> next = head;

typedef struct _node {
    int data;
    struct _node *next;
} node_t;

typedef struct {
    node_t *head;
    node_t *tail;
} LL_t;

//Post: inserts node with data x into location i of list L
void spliceinto(LL_t *L, int x, int i) {
    node_t *newNode1 = malloc(sizeof(node_t));
    newNode1->data = x;
    newNode1->next = NULL;
    if (i == 1) {
        newNode1->next = head;
        head = newNode1;
        return;
    }
    node_t *newNode2 = head;
    for (int j = 0; j < i - 2; i++) {
        newNode2 = newNode2 -> next;
    }
    newNode1->next = newNode2->next;
    newNode2->next = newNode1;
}

最佳答案

newNode1 -> next = L->head;
L->head = newNode1;

考虑到该函数无效。例如,一般来说newNode2->next可以等于NULL。结果是这个循环

for (int j = 0; j < i-2; i++){
    newNode2 = newNode2 -> next;
}

当节点数量小于 i 时,可能会出现未定义的行为。

还有一个错别字

for (int j = 0; j < i-2; i++){
                         ^^^^

必须有j++

此外,如果 tail 发生更改,您还应该记住更新函数中的 tail

这是一个演示程序,展示了如何编写该函数。

#include <stdlib.h>
#include <stdio.h>

typedef struct _node 
{
    int data;
    struct _node * next;
} node_t;

typedef struct 
{
    node_t * head;
    node_t * tail;
} LL_t;

void spliceinto( LL_t *ll, int i, int x )
{
    node_t *newNode = malloc( sizeof( node_t ) );

    if ( newNode != NULL )
    {
        newNode->data = x;

        if ( i == 1 || ll->head == NULL )
        {             
            newNode->next = ll->head;
            ll->head = newNode;
            if ( ll->head->next == NULL ) ll->tail = ll->head;
        }
        else
        {
            node_t *current = ll->head;
            for ( int j = 0; j < i - 2 && current->next != NULL; j++ )
            {
                current = current->next;
            }

            newNode->next = current->next;
            current->next = newNode;
            if ( newNode->next == NULL ) ll->tail = newNode;
        }
    }
}    

void display( LL_t *ll )
{
    for ( node_t *current = ll->head; current != NULL; current = current->next )
    {
        printf( "%d ", current->data );
    }        
    printf( "\n" );
}    

int main( void )
{
    LL_t ll = { NULL, NULL };

    for ( int i = 0; i < 10; i += 2 ) spliceinto( &ll, i + 1, i );
    for ( int i = 1; i < 10; i += 2 ) spliceinto( &ll, i + 1, i );

    display( &ll );
}    

程序输出为

0 1 2 3 4 5 6 7 8 9 

关于C - 代码表示头未声明 - 尝试将节点插入链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36120391/

相关文章:

c - 指向 const 的指针是否与 __restrict 具有相同的效果?

c - 关于指针和结构体的代码中的问题

data-structures - LinkedList 不提供基于索引的访问,那么为什么它有 get(index) 方法?

c - 如何使用链表初始化堆栈

linked-list - 在构建链表时如何保持对最后一个节点的可变引用?

c - 导致安全漏洞的缓冲区溢出示例

七星输出

c - 函数需要异常长的时间才能返回

C 无限指针循环(由重复值引起?)

c++ - 将返回的指针分配给另一个返回的指针?