c++ - 如何在 C++ 中检查整数单链表的对称性?

标签 c++ data-structures linked-list singly-linked-list

我对 C++ 中的单链表有疑问。

如果数组[0] = 数组[n], 数组[1] = 数组[n-1], ... 则整数数组[0..n] 称为对称数组

例如:1 2 3 4 5 4 3 2 1

那么,有什么方法可以检查整数单向链表的对称性吗?

我想过将它们的值复制到一个数组中,然后检查这个数组的对称性,但我认为这不好,因为链接列表的特征会丢失。

最佳答案

如果您所说的“简单链接”实际上是指单独链接,那么您必须复制其中的一半——无论是使用递归在堆栈上还是复制到数组。

bool is_symmetric(Node* p, int n)
{
    Value values[n / 2]; // use alloca or std::vector if your compiler doesn't support
    for (int i = 0; i < n / 2; ++i, p = p->next)
         values[i] = p->value;
    if ((n + 1) % 2) p = p->next; // for odd number of elements, middle one's ok
    for (; i >= 0; --i, p = p->next)
         if (values[i] != p->value)
             return false;
    return true;
}

注意:我还没有测试过这个,它可能会有一两个错误,但总体思路就在那里......

如果是双向链接,则更容易 - 迭代一半,然后在两个方向上迭代进行比较。

关于c++ - 如何在 C++ 中检查整数单链表的对称性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26601397/

相关文章:

c++ - 从 std::back_insert_iterator 派生?

c++ - glfw openGL c++ 窗口背景和标题

data-structures - 使用二次探测实现哈希表的原因

c - 从 C 中的链表返回字符串数组

c++ - 错误: cannot bind non-const lvalue reference of type ‘Position&’ to an rvalue of type ‘Position’

c++ - 链接问题 tinylibxml C++ Ubuntu

c++ - 使用 union 会有好处吗?

language-agnostic - 我们在实践中使用哈希表吗?

java - 如何将代码拆分为同一目录中的两个 .java 文件(使用类)?

c - 将头节点添加到单链表会产生段错误