码迷,mamicode.com
首页 > 编程语言 > 详细

剑指Offer - Python

时间:2019-06-20 22:34:22      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:def   构建   lse   red   lang   指针   style   top   rev   

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

 

剑指Offer - Python

标签:def   构建   lse   red   lang   指针   style   top   rev   

原文地址:https://www.cnblogs.com/WuSehun/p/11061774.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!