从类型 'struct node' 分配给类型 'struct node *' 时类型不兼容

Incompatible types when assigning to type 'struct node *' from type 'struct node'

我写了一个代码来在单向链表中插入一个节点。但它一直给我错误:

从类型 'struct node'

分配给类型 'struct node ' 时不兼容的类型
void insert(int d, int pos)
{
    int k=1;
    struct node *p,*q,*newNode;
    newNode = (struct node *)malloc(sizeof(struct node));
    if (newNode=NULL)
    {
        printf("Unable to allocate Memory");
        exit(0);
    }
    newNode->data = d;
    p = *head;
    if(pos == 1)
    {
        newNode->next=p;
        *head = newNode;
    }
    else
    {
        while((p!=NULL) && (k<pos))
        {
            k++;
            q=p;
            p = p->next;
        }
        q->next = newNode;
        newNode->next = p;
    }
}

它在网上给我同样的错误: p = *head;*head = newNode;

这是head

struct node {
    int data;
    struct node *next;
} *head;

任何解决方案?

对于这个 if 语句的初学者

if (newNode=NULL)

必须是比较而不是赋值

if ( newNode == NULL)

这些作业

p = *head;

*head = newNode;

不正确。看来你的意思是

p = head;

head = newNode;

还有这个if语句

if(pos == 1)
{
    newNode->next=p;
    *head = newNode;
}

应该改成

if(pos == 1 || head == NULL )
{
    newNode->next=p;
    *head = newNode;
}

注意表示位置的参数必须是无符号整数类型。例如 size_t。位置应该从 0 而不是 1 开始。

当函数依赖于全局变量时也是一个坏主意,例如在您的程序中函数依赖于全局指针 head.

使用你的全局指针头方法,我将按照下面的演示程序所示的方式编写函数。

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

struct node {
    int data;
    struct node *next;
} *head;

int insert( int d, size_t pos )
{
    struct node *new_node = malloc( sizeof( struct node ) );
    int success = new_node != NULL;
    
    if ( success )
    {
        struct node **current = &head;
        
        while ( *current != NULL && pos-- )
        {
            current = &( *current )->next;
        }
        
        new_node->data = d;
        new_node->next = *current;
        
        *current = new_node;
    }
    
    return success;
}

FILE * display( FILE *fp )
{
    for ( struct node *current = head; current != NULL; current = current->next )
    {
        fprintf( fp, "%d -> ", current->data );
    }
        
    fputs( "null", fp );
    
    return fp;
}

int main( void )
{
    insert( 2, 10 );
    insert( 0, 0 );
    insert( 1, 1 );
    insert( 3, 3 );
    
    putc( '\n', display( stdout ) ); 
}

程序输出为

0 -> 1 -> 2 -> 3 -> null

您在分配指针时取消引用指针,这导致了您的问题。

p = *head 中,您 想要 struct node *head 分配给 struct node *p,但您正在取消引用 head,这意味着您实际上是在分配 struct node headstruct node *p。要解决此问题,请不要在语句中使用 *

是一样的,但是反过来,当你做*head = newNode的时候。您取消引用 head,这意味着您正试图将 struct node *newNode 分配给 struct node head。此修复与上一个修复相同:省略 *.