1. 206. 反转链表
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """
pre = None cur = head while cur: tmp = cur.next cur.next = pre pre = cur cur = tmp return pre
2. 剑指 Offer 22. 链表中倒数第k个节点 ttps://leetcode-cn.com/problems/reverse-linked-list
class Solution(object): def getKthFromEnd(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """
#双指针,faster比slower快k个node
former, latter = head, head for i in range(k): former = former.next while former: former, latter = former.next, latter.next return latter
3. 876. 链表的中间结点
class Solution(object): def middleNode(self, head): """ :type head: ListNode :rtype: ListNode """
# 双指针,faster是slower的两倍
faster = slower = head while faster and faster.next: slower = slower.next faster = faster.next.next return slower
l1, l2 = head, head count = 0
while l1: count += 1 l1 = l1.next # count the length of linkedlist mid = count/2 # get the mid num for i in range(mid): l2 = l2.next return l2