我怎样才能只找到出现在列表中一次的元素并返回基数?例如,如果我的列表由{3,2,1,1,2,4}组成,我希望返回计数器为4而不是6,因为我们不计算重复的数字.这是我到目前为止编写的代码.
How can i find only the elements that appears once in the list and return the cardinal number?For example if my list consist of {3,2,1,1,2,4} i expect for return the counter to be 4 and not 6 cause we do not count the duplicate numbers. Here is the code that i have written so far.
struct Node { int data; struct Node *next; }; int Find_cardinal(struct Node *start) { struct Node *ptr1, *ptr2 ptr1 = start; int counter=0; /* Pick elements one by one */ while (ptr1 != NULL && ptr1->next != NULL) { ptr2 = ptr1; /* Compare the picked element with rest of the elements */ while (ptr2->next != NULL) { /* If duplicate */ if (ptr1->data == ptr2->next->data) { break; } else //do what? ptr2 = ptr2->next; } ptr1 = ptr1->next; } return counter; } 推荐答案您的函数实现错误.
即使是第一个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.更多推荐
在C中找到列表的基数
发布评论