在提供源代码,而条件是指(其中指针被存储的)指针的地址和struct node **head
指向一个静态位置在main()
但(&(*temp)->next)
指向所分配的最后一个项目。
要比较链接列表中的项目,您应该比较指针struct node *
而不是指针struct node **
的地址。
在Count()
功能,因为*head
存在(未相比 NULL),计数器count
应该从1开始,并以统计圆形列表中的所有项目,你应该temp = &(*head);
,而不是下一个项目temp = &((*head)->next);
启动。
这里后面是一个"Minimal, Complete, and Verifiable example"。
#include <stdio.h>
#include <stdlib.h>
#define NODE_MAX (5)
struct node {
struct node *next;
};
int Count(struct node **head)
{
printf("entered");
struct node **temp;
int count = 1; // at least the '*head' node exists
temp = &(*head);// &((*head)->next);
while (((*temp)->next) != *head) // use '*head'
{
printf("entered");
temp = &((*temp)->next);
count++;
}
return count;
}
int main()
{
struct node array[NODE_MAX];
struct node *head, *temp;
head = &(array[0]);
temp = head;
for(int i=1;i<NODE_MAX;i++) {
temp->next = &(array[i]);
temp = temp->next;
}
temp->next = &(array[0]);
printf("\nCount = %d\n",Count(&head));
system("pause");
return (0);
}
这将是更易于管理链表在指针水平,如下面的例子:
int Count2(struct node **head)
{
printf("entered");
struct node *temp;
int count = 1;
temp = (*head); // pointers to the first
while (temp->next != *head) // direct pointer comparison
{
printf("entered");
temp = temp->next; // natural linked-list exploration
count++;
}
return count;
}