c - 单个链表的显示不如预期
问题描述
这段代码运行良好,但某些行有问题,结果我得到这样的输出
输入节点数 5 将元素输入列表 1 2 3 4 5 元素为 1 1 2 3 4 5 进程返回 0 (0x0) 执行时间:5.956 s 按任意键继续。
问题 - 如您所见,第一个元素被打印了两次。
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*first=NULL;
void create(int a[],int n)
{
int i;
struct node *x,*far;
first=(struct node*)malloc(sizeof(struct node));
first->data=a[0];
first->next=NULL;
far=first;
for(i=0;i<n;i++)
{
x=(struct node*)malloc(sizeof(struct node));
x->data=a[i];
x->next=NULL;
far->next=x; //connects the node far to x
far=x; //shifts the node far to x now far will be pointing to x
}
}
void display(struct node *p)
{
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
}
int main()
{
int a[10],n=0,i;
printf("enter the no of nodes\n");
scanf("%d",&n);
printf("enter the elements to the list\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
create(a,n);
printf("the elements are\n");
display(first);
}
解决方案
您正在将数组的第一个元素分配到此处的列表中
first->data=a[0];
这里最初i
是 0
x->data=a[i];
您可以通过从 1 开始循环来停止它
for(i=0;i<n;i++) /* to be changed to */
for(i=1;i<n;i++)
推荐阅读
- python - Flask-SQLAlchemy: Trying to use query.paginate() in reverse order
- r - 成功部署到 shinyapp.io 后打开我的闪亮应用程序时如何解决此错误?
- c# - Net Core:为所有表自动代码生成创建通用存储库接口 Id 映射
- c - 无法在第二个 ''FOR'' 上获得 ''i'' 的值
- python-3.x - 找不到 Pip3 安装的包
- apache-kafka - 如何防止 Kafka Connect JDBC 连接器从开始/最早的消息读取,而只读取最新的消息?
- java - Issue with de-serialization from json to object containing enums
- google-app-engine - 如何从 Google Cloud SDK Repo 中获取我的 SQL 数据库
- angular - Snackbar 在部署时填满整个屏幕
- oauth-2.0 - how to generate X-RapidAPI-Key without accessing https://rapidapi.com via Browser