很抱歉提出这样的问题(编程新手):
我想用findMid方法找到链表的中间元素。很抱歉解释不清楚,因为英语不是我的母语。谢谢:)
我的代码正在创建链表,我想通过一次遍历找到链表的中间元素。到目前为止,我通过向google寻求帮助,实现了一个使用指针概念的函数,该函数是:
def findMid(self):
slowPtr = self.__head
fastPtr = self.__head
if not self.__head is not None:
while fastPtr is not None and fastPtr.next is not None:
fastPtr = fastPtr.next.next
slowPtr = slowPtr.next
return slowPtr
但它给我的回报是
我剩下的链表代码是:
^{pr2}$
要在一次单次过程中找到中间的数字,您需要为长度保留一个计数器,并存储所看到的元素的完整列表。然后,可以通过
flattened_results[counter//2]
找到中间的数字:输出:
^{pr2}$相关问题 更多 >
编程相关推荐