【问题标题】:Linked list using C for insertion of a node at nth position [closed]使用 C 的链表在第 n 个位置插入节点 [关闭]
【发布时间】:2016-02-24 18:05:43
【问题描述】:

我使用 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();
}

【问题讨论】:

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


【解决方案1】:

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

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

改写

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

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

没有参数的main函数也应该声明为

int main( void )

函数 print 应该像这样声明

void print( void );

【讨论】:

  • thanxx mate.. 成功了..
  • @VishalBarkakati 完全没有。我们初学者应该互相帮助。:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多