在insert函数里,node->next=p->next那步在vscode里会报错是怎么回事?

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

typedef struct Node{
    int data;
    struct Node *next;
} Node;

Node *insert(Node *head, int pos,int val){
    Node new_head, *p = &new_head,*node = getNewNode(val);
    new_head.next = head;
    for(int i = 0; i < pos ; i++) p = p->next;
    node->next = p->next;
    p->next = node;
    return new_head.next;
}
Node *getNewNode(int val){
    Node *p = (Node*)malloc(sizeof(Node));
    p->data = val;
    p->next = NULL;
    return p;
}
void clear(Node *head){
    if(head == NULL) return;
    for(Node *p = head,*q;p; p = q){
        q = p->next;
        free(p);
    }
    return;
}

void output_linklist(Node *head){
    int n = 0;
    for(Node *p = head;p;p = p->next) n +=1;
    for(int i = 0;i < n; i ++){
        printf("%3d",i);
        printf("  ");
    }
    printf("\n");
    for(Node *p = head; p; p = p->next){
        printf("%3d",p->data);
        printf("->");
    }
    printf("\n\n\n");
    return;
}

int main(){
    srand(time(0));
    #define MAX_OP 20
    Node *head = NULL;
    for(int i =0; i < MAX_OP; i++){
        int pos = rand()%(i + 1), val = rand()%100;
        printf("insert %d at %d to linklist\n",val,pos);
        head = insert(head,pos,val);
        output_linklist(head);
    }
    return 0;
}
阅读 835
1 个回答

这个回答算是对楼上问题评论区小伙伴的回答补充,在insert函数之前添加一个函数声明,或者将getNewNode函数的定义移到insert函数的前面就可以运行了。
比如说这样:

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

typedef struct Node{
    int data;
    struct Node *next;
} Node;

Node *getNewNode(int val){
    Node *p = (Node*)malloc(sizeof(Node));
    p->data = val;
    p->next = NULL;
    return p;
}

Node *insert(Node *head, int pos,int val){
    Node new_head, *p = &new_head,*node = getNewNode(val);
    new_head.next = head;
    for(int i = 0; i < pos ; i++) p = p->next;
    node->next = p->next;
    p->next = node;
    return new_head.next;
}

void clear(Node *head){
    if(head == NULL) return;
    for(Node *p = head,*q;p; p = q){
        q = p->next;
        free(p);
    }
    return;
}

void output_linklist(Node *head){
    int n = 0;
    for(Node *p = head;p;p = p->next) n +=1;
    for(int i = 0;i < n; i ++){
        printf("%3d",i);
        printf("  ");
    }
    printf("\n");
    for(Node *p = head; p; p = p->next){
        printf("%3d",p->data);
        printf("->");
    }
    printf("\n\n\n");
    return;
}

int main(){
    srand(time(0));
    #define MAX_OP 20
    Node *head = NULL;
    for(int i =0; i < MAX_OP; i++){
        int pos = rand()%(i + 1), val = rand()%100;
        printf("insert %d at %d to linklist\n",val,pos);
        head = insert(head,pos,val);
        output_linklist(head);
    }
    return 0;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进