[英]Node elements are not printing in Single Linked List Program
我在这里用TurboC ++创建了一个C程序。 这个简单的程序目标是只创建一个链表,在列表的末尾插入每个元素,然后打印节点的值。(已编辑该程序进行了一些更改,以使我更容易理解,但仍然存在问题)存在未进行优先处理的节点)问题是,某些节点元素未打印
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<ctype.h>
#include<conio.h>
struct node
{
int data;
struct node *link;
};
typedef struct node ND;
void main()
{
ND *start,*current,*temp;
start=NULL;
do
{
temp=(ND*)malloc(sizeof(ND));
printf("\n Enter Node Value");
scanf(" %d",&temp->data);
temp->link=NULL;
if(start==NULL)
{
start=current=temp;
}
else
{
current->link=temp;
current=temp;
}
fflush(stdin);
printf("\nDo You Want TO Continue?(Y/N)");
}while(toupper(getchar())!='N');
current=start;
printf("\nThe Elements OF Linked List ARE:");
while(current!=NULL)
{
printf(" %d",current->data);
current=current->link;
}
}
您从错误的元素打印列表。 你应该从头开始。 喜欢:
temp1 = head;
while(temp1!=NULL)
{
printf(" %d",temp1->data);
temp1=temp1->link;
}
顺便说一下,您的head元素将始终为NULL。 这是将元素添加到列表的正确方法:
if (head == NULL)
{
head = temp;
}
else
{
temp1 = head;
while (temp1->link != NULL)
{
temp1 = temp1->link;
}
temp1->link = temp;
}
该程序现已正常运行,我进行了一些更改以使该程序更易于理解。以下是代码:
#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node *link;
};
typedef struct node ND;
void main()
{
ND *head,*tail,*temp1;
int n;
char ch;
printf("\nEnter Data?(y/n)\n");
scanf(" %c",&ch);
fflush(stdin);
if(ch=='y' || ch=='Y')
{
tail=(ND*)malloc(sizeof(ND));
printf("\n Enter Node Value");
scanf(" %d",&n);
tail->data=n;
tail->link=NULL;
head=tail;
printf("\nDo You Want TO Continue?(Y/N)");
scanf(" %c",&ch);
fflush(stdin);
}
while(ch=='y' || ch=='Y')
{
printf("\n Enter Node Value");
scanf(" %d",&n);
tail->link=(ND*)malloc(sizeof(ND));
tail->link->data=n;
tail->link->link=NULL;
tail=tail->link;
printf("\nEnter More Data?(y/n)\n");
scanf(" %c",&ch);
fflush(stdin);
}
printf("\nElements Of Linked List Are:");
temp1=head;
while(temp1!=NULL)
{
printf(" %d",temp1->data);
temp1=temp1->link;
}
printf("\n");
fflush(stdout);
getch();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.