作为链表的堆栈中元素的相邻外观次数

How many adjacent appearances of an element in a stack as linked list?

本文关键字:外观 链表 堆栈 元素      更新时间:2023-10-16

这是我的函数;它应该计算列表中元素的连续出现次数。它所做的是将它们数加一。假设我们有 1->1->2->3->NULL;它应该输出 2,但它输出 3。任何帮助将不胜感激。

void consecutive(node *current) {
    int con=0;
    while (current && current->next) {
        con++;
        if (current->next==NULL)
            break;
        current=current->next;
    }
    cout<<"Number of adjacent appearances is : "<<con<<endl;
}

当您不提供正在使用的结构/类时,很难提供帮助。 如果要查找具有相同值的连续元素,可以执行以下操作:

void consecutive(node *current) {
    int con=0;
    if( current ) {
        auto value = current->number;
        for( current = current->next; current && ( current->number == value ); current = current->next )
            ++con;
    }
    cout<<"Number of adjacent apearances is : "<<con<<endl;
}