首页 > 解决方案 > 计算C中列表中的不同元素

问题描述

我想计算一个列表的所有不同数字。例如,如果我的列表由 {1,2,1,1,3,4} 组成,我需要返回 4。这是我编写的代码。

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



int count_distinct(Node_t * start) 
{ 
    Node_t  *ptr1, *ptr2; 
    ptr1 = start; 
    int counter=0;
    /* pick one element*/
    while (ptr1 != NULL && ptr1->next != NULL) 
    { 
        ptr2 = ptr1; 
  
        /* compare picked element with the rest */
        while (ptr2->next != NULL) 
        { 
            /* If duplicate */
            if (ptr1->data == ptr2->next->data) 
            { 
                break;
            } 
            else 
                ptr2 = ptr2->next; 
                counter++;
        } 
        ptr1 = ptr1->next; 
    } 
return counter;
} 

标签: clinked-list

解决方案


推荐阅读