2016-11-24 22 views
1

导致无限循环的函数。它无法返回节点的数量。我哪里错了?使用双指针的C++中循环列表的大小

int Count(struct node **head) 
    { 

    printf("entered"); 
    struct node **temp; 
    int count = 0; 
    temp = &((*head)->next); 
    while ((&(*temp)->next) != head) 
    { 
     printf("entered"); 
     temp = &((*temp)->next); 
     count++; 
    } 
return count; 
    } 

回答

0

在提供源代码,而条件是指(其中指针被存储的)指针的地址和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; 
}