【发布时间】:2015-09-25 08:17:26
【问题描述】:
我对 python 比较陌生,正在尝试了解如何将 Python 与 C/C++ 联系起来。考虑这个问题:检查给定的链表是否是回文。从这个source,我找到了一个非常有效的解决方案:
// Initial parameters to this function are &head and head
bool isPalindromeUtil(struct node **left, struct node *right)
{
/* stop recursion when right becomes NULL */
if (right == NULL)
return true;
/* If sub-list is not palindrome then no need to
check for current left and right, return false */
bool isp = isPalindromeUtil(left, right->next);
if (isp == false)
return false;
/* Check values at current left and right */
bool isp1 = (right->data == (*left)->data);
/* Move left to next node */
*left = (*left)->next;
return isp1;
}
// A wrapper over isPalindromeUtil()
bool isPalindrome(struct node *head)
{
isPalindromeUtil(&head, head);
}
基本上一个指向指针的指针被分配到前面(左指针),一个指针被分配到列表的末尾(右指针)。一旦指针到达它们各自的位置,它们就会递归并找到匹配的值。这里,*left 维护指针的状态,该指针的值通过递归循环持续存在。 python 中的一种解决方案是将左指针与布尔值一起传回。但是,如果使用多个指向指针的指针,则返回元素的数量会爆炸!糟糕的设计。还有其他方法吗?
编辑:
非常感谢您的回复!我忘了提到我不是想在这里解决回文问题。我试图了解是否存在使用指针的 Pythonic 等效方式。我想要理解的是,如果向我提出一个问题,它使用链表等数据结构,我应该尝试将其转换为其他数据结构,如列表,还是我需要创造性并使用解决问题相同的数据结构。由于指针指针在链表和 BST 中是非常重要的概念,对于这个概念是否有等效的解决方案或变通方法?
编辑#2: 我想出的粗略代码如下。但是,left_ptr 仍然停留在相同的位置,因为它是一个指针而不是指向指针的指针:
def palindrome_utils(self, left_ptr, right_ptr):
if right_ptr is None:
return True
prev_result = self.palindrome_utils(left_ptr, right_ptr.get_link())
cur_result = left_ptr.get_data() == right_ptr.get_data()
left_ptr = left_ptr.get_link()
return cur_result and prev_result
def palindrome(self):
return self.palindrome_utils(self.head, self.head)
【问题讨论】:
-
另一种使用指针的方法,或者另一种确定单词是否为回文的方法?
-
当你说“链表”时,你是在使用
collections.deque吗? -
尝试在 Python 中复制 C/C++ 数据结构和算法并不总是有用的。请记住,由于解释器的开销,当用 Python 而不是 C/C++ 实现时,各种算法的(相对)速度可能会有很大的不同。例如,与在 Python
for或while循环中对列表项进行操作相比,对序列进行操作的 Python 库函数可以非常快,因为该函数可以以 C 速度处理列表。 TL; DR:当你用 Python 编写代码时,不要尝试编写 C/C++。
标签: python c pointers python-3.x