为什么我插入链表的代码在第 3 项上失败?

Why does my code to insert into linked list fail on the 3rd item?

我正在尝试编写函数以在第 n 个位置增加值并从第 n 个位置删除。当我测试我的插入函数时它似乎运行良好,但是当我尝试在第三个位置添加一个值时它卡住了。

当我注释掉它时,代码运行良好。为什么会这样?

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

// Node Struct
struct Node{
    int data;
    struct Node* next;
};

struct Node *head;  // Global head of the struct

//Function to create New Node with Data and return it
struct Node* NewNode (int data){
    struct Node* temp=(struct Node*)malloc(sizeof(struct Node));
    temp->data=data;
    temp->next=NULL;
    return temp;

}
// Function to add new value in nth Position
void AddN(int data,int n){
    struct Node* temp = NewNode(data);
    struct Node *temp1= head;
    if(n==1){
        temp->next=head;
        head=temp;
    }
    else{
        for(int i=0;i=n-2;i++){
            temp1=head->next;
        }
        temp->next=temp1->next;
        temp1->next=temp;
    }
}

void Print(){
    struct Node* tempHead=head;
    while(tempHead != NULL){
        printf("%d ", tempHead->data);
        tempHead = tempHead->next;
    }
}

void main(){
    head=NULL; //Empty List
    AddN(1,1); //List: 1
    AddN(2,2); //List: 1 2
    //AddN(3,3); //List: 1 2 (3) ( Doesn't work)
    AddN(4,1); //List: 4 1 2 
    AddN(5,2); //List: 4 5 1 2 
    Print();
}

一个明显的错误是 for 循环:

for(int i=0;i=n-2;i++)

此表达式 i=n-2 不检查是否相等,而是将值 n-2 设置为 i。也许 i < n-2 应该在那里?

并且在 for 循环体中这个赋值 temp1=head->next; 也没有任何建设性的作用。

for 循环后指针 temp1 的值可能为 NULL,具体取决于传递给函数的索引。以下行 temp->next=temp1->next; 取消引用导致未定义行为的指针。

另一个问题是,如果你插入一个索引大于 1 的节点,你不会检查 head 是否为 NULL。