c - 使用 C 在第 n 个位置插入节点的链表

标签 c struct linked-list declaration singly-linked-list

我使用 C 编写了这段代码,我是编程世界的新手,所以请帮助我解决我的错误。我正在取消引用指向不完整类型的指针。我需要进行哪些更改才能运行此代码?

enter code here
#include <stdio.h>
#include <stdlib.h>
struct {
int data;
struct node* next;
};
struct node* head;

void Insert(int data, int n)
{
int i;
struct node* temp1, *temp2;
temp1 = (struct node*)malloc(sizeof(struct node));
temp1->data = data;
temp1->next = NULL;
if(n==1)
    {
        temp1->next = head;
        head = temp1;
        return;
    }

 temp2 = head;
  for(i=0; i<n-2; i++)
  {
      temp2 = temp2->next;
  }
  temp1->next = temp2->next;
  temp2->next = temp1;

}

void print()
{
struct node* temp = head;
while(temp != NULL)
{
    printf("%d", temp->data);
    temp = temp->next;
}
print("\n");
}

int main()
{
head = NULL;
Insert(2,1);
Insert(3,2);
Insert(4,1);
Insert(5,2);
Insert(1,3);
Print();
}

最佳答案

您在结构定义中省略了标记名称节点

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

改写

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

请考虑到,通过与数组的类比,列表中的位置从 0 开始会更好。

不带参数的 main 函数也应声明为

int main( void )

函数 print 应该这样声明

void print( void );

关于c - 使用 C 在第 n 个位置插入节点的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35609708/

相关文章:

python - 从服务器错误地拆封邮件。 Python。 socket

c++ - 使用用户输入创建对象

c++ - 为什么结构的 sizeof 不等于每个成员的 sizeof 之和?

java - Java链表实现中的head是什么

c - 在 C 中分隔多个名字和/或姓氏

c - 对指针进行类型转换以更改其大小(以字节为单位)

检查一个字符串是否是另一个字符串的子字符串

c - 内核写入进程内存导致蓝屏

c++ - 反向链表算法

c++ - 如何在 C++ 中修复 "Segmentation fault(core dump)"?