首页 > 解决方案 > 单个链表的显示不如预期

问题描述

这段代码运行良好,但某些行有问题,结果我得到这样的输出

输入节点数 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);
}

标签: clinked-list

解决方案


您正在将数组的第一个元素分配到此处的列表中

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++)

推荐阅读