在提供源代碼,而條件是指(其中指針被存儲的)指針的地址和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;
}