# 方法一: defreverseWords(s): tmp = s.split(" ") # ["Let's", 'take', 'LeetCode', 'contest'] n = len(tmp) for i inrange(n): tmp[i] = list(tmp[i]) for item in tmp: i = 0 j = len(item) - 1 while i <= j: item[i],item[j] = item[j],item[i] i += 1 j -= 1 for i inrange(n): tmp[i] = "".join(tmp[i]) return" ".join(tmp)
# 利用列表 : 因为链表没有下标,故可以先遍历存到列表中 时间空间复杂度为O(n) defmiddleNode(head): A = [head] while A[-1].next: A.append(A[-1].next) return A[len(A) // 2]
# 单指针法 : 先遍历链表拿到链表长度n,当指针指到n/2时,返回当前值 defmiddleNode2(head): n,cur = 0,head while cur: n += 1 cur = cur.next k,cur = 0,head while k < n // 2: k += 1 cur = cur.next return cur
# 双指针法: 快慢指针法,遍历链表,慢指针一次走一步,快指针一次走两步,当快指针走到结尾时,慢指针走到链表中间 defmiddleNode3(head): slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow