剑指Offer - Python

014-链表中倒数第k个结点

用快慢指针:p2p1先走k-11k:间隔了k-1步,然后再一起走,当p2为最后一个时,p1就为倒数第k个数

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def FindKthToTail(self, head, k):
        if not head or k<=0: return None
        p1 = head
        p2 = head
         #设置两个指针,p2指针先走(k-1)步,然后再一起走
        while (k-1)>0:
            if (p2.next != None):
                p2 = p2.next
                k -= 1
            else:
                return None
        while (p2.next != None): # 等同while p2.next:
            p1 = p1.next
            p2 = p2.next
        return p1

015-反转链表(链表转化赋值

思路:变化node.next

假设翻转1->2->3->4->5,(54321)

重要:

  • 1.构建辅助节点head
  • 2.我们将pnext指向tpnext
  • 3.tpnext指向headnext
  • 4.headnext指向tp
class ListNode:
     def __init__(self, x):
            self.val = x
            self.next = None

class Solution:
    # 新链表的表头,不是head,是head.next
    def ReverseList(self, pHead):
        if not pHead:return None
        #构建辅助节点head
        head = ListNode(0)
        head.next = pHead
        p = pHead
        while p.next != None:
            #链表节点转化操作(重要)
            tp = p.next
            p.next = tp.next
            tp.next = head.next
            head.next = tp
        return head.next

猜你喜欢

转载自www.cnblogs.com/WuSehun/p/11061774.html