T22-链表中倒数第k个节点
注意走(k-1)步的循环中,判断p==None就返回,即链表长度小于k的情况
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindKthToTail(self, head, k):
# write code here
if k<1 or not head:
return None
p,p1 = head,head
for i in range(k-1):
p = p.next
if not p:
return None
while p.next:
p = p.next
p1 = p1.next
return p1
T24-反转链表
非递归写法 py2
对于看似复杂的问题,看分解的每一部分怎么操作也许是最好的方法。 此题也是,只关注链表的每个节点,这个单向链表的节点,它的后节点指向变为哪里,而不关心多个节点是怎样连接的。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
if not pHead or not pHead.next:
return pHead
ppre,pnext=None,None
p = pHead
while p:
pnext = p.next
p.next = ppre
ppre = p
p = pnext
return ppre
递归写法 py2
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
return self._reverse(pHead,None)
def _reverse(self,node,prev=None):
if not node:
return prev
n = node.next
node.next = prev
return self._reverse(n,node)