且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C中找到列表的基数

更新时间:2023-02-26 19:10:38

您的函数实现错误.

即使是第一个while循环中的情况,

Even the condition in the first while loop

while (ptr1 != NULL && ptr1->next != NULL)

是不正确的,因为如果列表仅包含一个节点,则不会执行循环,该函数将返回0.

is incorrect because if the list contains only one node the loop will not be executed and the function will return 0.

在该函数中,变量 counter 未被更改.

And within the function the variable counter is not being changed.

这里是一个演示程序,展示了如何实现更好地命名为 count_distinct 之类的函数 Find_cardinal .

Here is a demonstrative program that shows how the function Find_cardinal that is better to name like count_distinct can be implemented.

#include <stdio.h>
#include <stdlib.h>

struct Node 
{ 
    int data; 
    struct Node *next; 
}; 
typedef struct Node Node_t;

size_t assign( Node_t **head, const int a[], size_t n )
{
    while ( *head )
    {
        Node_t *tmp = *head;
        head = &( *head )->next;
        free( tmp );
    }
    
    size_t i = 0;
    
    for ( ; i < n && ( *head = malloc( sizeof( Node_t ) ) ) != NULL; i++ )
    {
        ( *head )->data = a[i];
        ( *head )->next = NULL;
        head = &( *head )->next;
    }
    
    return i;
}

size_t count_distinct( const Node_t *head )
{
    size_t n = 0;
    
    for ( const Node_t *current = head; current != NULL; current = current->next )
    {
        const Node_t *prev = head;
        
        while ( prev != current && prev->data != current->data )
        {
            prev = prev->next;
        }
        
        if ( prev == current ) ++n;
    }
    
    return n;
}

FILE * display( const Node_t *head, FILE *fp )
{
    for ( ; head != NULL; head = head->next )
    {
        fprintf( fp, "%d -> ", head->data );
    }
    
    fputs( "null", fp );
    
    return fp;
}

int main(void) 
{
    Node_t *head = NULL;
    int a[] = { 1, 2, 1, 1, 3, 4 };
    
    assign( &head, a, sizeof( a ) / sizeof( *a ) );
    
    fputc( '\n', display( head, stdout ) );
    
    printf( "There are %zu distinct data in the list.\n", count_distinct( head ) );
    
    return 0;
}

程序输出为

1 -> 2 -> 1 -> 1 -> 3 -> 4 -> null
There are 4 distinct data in the list.