p = q = head while q and q.next: pre = p p = p.next q = q.next.next if q: pre = p p = p.next pre.next = None def reverse(p): newHead = ListNode('') while p: q = p p = p.next q.next = newHead.next newHead.next = q return newHead.next p = reverse(p) q = head while q.next: if q.val != p.val: return False q = q.next p = p.next return True head = ListNode.create_list([1,2, 1,2]) print(Solution().isPalindrome(head))
向右旋转 1 步: 2->0->1->NULL 向右旋转 2 步: 1->2->0->NULL 向右旋转 3 步: 0->1->2->NULL 向右旋转 4 步: 2->0->1->NULL ''' class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: if not head: return head p=head i=1 while i<=k: if not p.next: k=k%i i=1 p=head else: p=p.next i+=1 q=head if k == 0: return head while p.next: p=p.next q=q.next newHead=q.next q.next=None p.next=head return newHead head=ListNode.create_list([1]) print(Solution().rotateRight(head,1))
return c def sortedListToBST(self, head: ListNode) -> TreeNode: ''' 根据中序遍历的顺序去构造二叉树,正好中序遍历的顺序就是链表的顺序,中序遍历是递归的 ''' size = self.findSize(head) def convert(l, r): nonlocal head if l > r: return None mid = (l + r) // 2 # 中序遍历左子树 left = convert(l, mid - 1) # 构造左子树之后构造当前节点 node = TreeNode(head.val) node.left = left head = head.next node.right = convert(mid + 1, r) return node return convert(0, size - 1) head = ListNode.create_list([-10, -3, 0, 5, 9]) Solution().sortedListToBST(head).printTree()