剑指Offer - Python
2020-12-13 02:55
标签:def 构建 lse red lang 指针 style top rev 014-链表中倒数第k个结点 用快慢指针:p2比p1先走k-1(1到k:间隔了k-1)步,然后再一起走,当p2为最后一个时,p1就为倒数第k个数 015-反转链表(链表转化赋值) 思路:变化node.next 假设翻转1->2->3->4->5,(54321) 重要: 剑指Offer - Python 标签:def 构建 lse red lang 指针 style top rev 原文地址:https://www.cnblogs.com/WuSehun/p/11061774.htmlclass ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def FindKthToTail(self, head, k):
if not head or kreturn 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
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