【发布时间】:2018-04-01 08:51:36
【问题描述】:
我想在一个循环链表中找到两个节点之间的距离(它们之间的节点数)。
节点在哪里:
typedef struct node
{
int data;
struct node *next;
}nodal;
nodal *distance(nodal *start)
{
int n1,n2,d1=0,d2=0,c=0;
if(start==NULL)
{
printf("\nList is empty");
}
else
{
printf("\nEnter the fist node element : ");
scanf("%d",&n1);
printf("\nEnter the second node element : ");
scanf("%d",&n2);
nodal *ptr=start;
while(ptr->next!=start)
{
c++;
if(ptr->data==n1)
{
d1=c;
}
if(ptr->data==n2)
{
d2=c;
}
}
}
printf("The distance between two nodes is %d",(d2-d1));
return start;
}
我没有给出任何输出。
还假设循环列表是否包含以下数据:
1,2,3,4,5,6,7,8,9
如果我提供意见
第一个节点元素为 9
第二个节点元素为 4
那么这个算法就行不通了。 有什么改变的建议吗?
【问题讨论】:
-
typo ,你在两个
if语句中都与 n1 进行比较 -
仍然没有输出@JoshGreifer
-
在第二种情况下,您有一个错字:必须是 n2。
-
无输出是什么意思?程序挂起?
-
是的 @0andriy 它挂了
标签: c data-structures linked-list circular-list