我想知道为什么newNode在此功能中不会消失?

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

typedef struct node {
    float hs;
    float sm;
    struct node *next;
}Node;

Node* InsertNode(Node* head, int index, float hs, float sm){
    if(index < 0) return NULL;

    int currIndex = 1;
    Node* currNode = head;
    while (currNode && index > currIndex) {
        currNode = currNode->next;
        currIndex++;
    }

    if (index > 0 && currNode == NULL) return NULL;

    Node* newNode = (Node*) malloc(sizeof(Node));
    newNode->hs = hs;
    newNode->sm = sm;

    if(index == 0){
        newNode->next = head;
        head = newNode;
    }

    else {
        newNode->next = currNode->next;
        currNode->next = newNode;
    }

    return head;
}

void Display(Node* head) {
    Node* currNode = head;
    while(currNode != NULL){
        printf("(%.2f, %.2f ) ", currNode->hs, currNode->sm);
        currNode = currNode->next;
    }
}

int main(){
    Node* poly1 = NULL;
    Node* poly2 = NULL;
    poly1 = InsertNode(poly1, 0, 5, 4);
    poly1 = InsertNode(poly1, 1, 6, 3);
    poly1 = InsertNode(poly1, 2, 7, 0);
    Display(poly1);
    getch();
    return 0;
}


我试图编写一个用于插入元素的函数。我知道局部变量在调用函数结束后会消失,但是它仍然有效吗?
请帮我解决这个问题。

最佳答案

当您调用-> poly1 = InsertNode(poly1, 1, 6, 3);时,poly1已经是头,而head->next为NULL,因此在这些行中:

Node* currNode = head;
while (currNode && index > currIndex) {
    currNode = currNode->next;
    currIndex++;
}


您正在将currNode指向NULL,之后它导致:

if (index > 0 && currNode == NULL) return NULL;

08-16 08:08