首页 > 解决方案 > 编写一个函数接受 2 个参数——指针头或尾加上链表的遍历方向

问题描述

这是我定义和初始化链表的方式

struct listrec
{
    struct listrec    *prev;
    float       value;
    struct listrec    *next;
};

listrec *head, *tail;

int main() {
int number;
cin >> number;
float content = 2.0;
    for (float i = 0; i < number; i++)
    {
        if (i == 0)
        {
            head = new listrec;
            head->prev = nullptr;
            head->value = 1.0;
            head->next = nullptr;
            tail = head;
        }
        else
        {
            auto *newNode = new listrec;
            newNode->value = content++;
            newNode->next = nullptr;
            newNode->prev = tail;
            tail->next = newNode;
            tail = tail->next;
        }
    }
return 0;
}

这就是链表的样子

在此处输入图像描述

我需要“编写一个函数,它接受两个输入参数——指针头或尾加上一个要遍历的方向的参数——遍历链表并返回列表中元素的数量。

我不知道如何编写这样的函数……</p>

我知道,如果我想计算第一个节点的元素数量,那么我可以编写这样的函数:

float listSize(listrec* head)
{
    int count = 0; 
    listrec* current = head; // Initialize current  
    while (current != NULL)
    {
        count++;
        current = current->next;
    }
    return count;
}

或者,如果我想从最后一个元素开始计算元素,那么

float listSize2(listrec* tail)
{
    int count = 1;
    listrec* current = tail;
    while (tail->prev != NULL)
    {
        count++;
        tail = tail->prev;
    }
    return count;
}

但是我怎样才能将这两者结合起来呢?任何提示将不胜感激!

标签: c++functionlinked-listtraversal

解决方案


这是函数,假设是一个双向链表:

enum class Direction {FORWARD, REVERSE};

struct Node
{
    Node * previous;
    Node * next;
};

unsigned int Count(Node * p_begin, Direction traverse_dir)
{
    unsigned int node_count = 0U;
    while (p_begin != nullptr)
    {
        ++node_count;
        if (traverse_dir == FORWARD)
        {
            p_begin = p_begin->next;
        }
        else
        {
            p_begin = p_begin->previous;
        }
    }
    return node_count;
}

根据要求,该函数采用 2 个参数,一个指向头节点或尾节点的指针,以及一个方向并返回遍历的节点数量。

该函数从传递的指针开始,然后向前或向后(取决于方向参数),并递增节点计数器。当遇到空指针时循环停止,这通常表示列表的开始或结束。

由于只使用了一个节点类,因此可以从 Node 继承来制作各种列表类型:

struct Integer_Node : public Node
{
    int data;
};

数据字段在遍历列表时不起任何作用,因此从基本节点对象中删除。


推荐阅读