我编写了以下代码来确定我的链接列表是否为回文。 我采取的步骤是:
def isPalindrome(self, head: ListNode) -> bool:
if head == None:
return True
#Finding the number of nodes in my linked list
length_ll = 0
curr = head
while curr:
length_ll +=1
curr = curr.next
#initializing head2 to be the midpoint node in the linked list
mid_point = len(length_ll)//2
#reversing second half of linked list
head2 = mid_point + 1. #Can I write this line?
prev = head2
curr = head2
nex = head2.next
while nex:
curr = nex
curr.next = prev
nex = nex.next
prev = curr
head2.next = None
#comparing nodes of first and second half of linked list to determine if LL is a palindrome
curr = head
curr2 = head2
while curr2:
if curr2.val != curr.val:
return False
我有两个问题:
所以@shorya sharma的道具他们的解决方案肯定是一条路要走
也就是说直接回答你的问题。不,您不能添加该行。 问题是中点是一个整数,头2必须是一个ListNode
相反,将该行替换为:
我是这里的新手,所以请告诉我是否禁止发布其他网站的链接
您将在此处找到有关如何解决此问题的详细讨论:https://leetcode.com/problems/palindrome-linked-list/discuss/?currentPage=1&orderBy=most_votes&query=
相关问题 更多 >
编程相关推荐