链表中倒数第k个节点
输入一个链表,输出该链表中倒数第k个结点。
思路:由于链表只能从前往后遍历,所以我们可以先求出链表的总长度N,然后利用第N-k个节点就是我们需要的来解决。
首先,统计链表的长度有两种方法,循环或者递归。分别如下:
#循环方式实现
def getSingleLinkedListNodeCount(self,node):
if node == None:
return 0
if node.next == None:
return 1
p = node
count = 0
while p:
count += 1
p = p.next
return count
#递归实现
def getSingleLinkedListNodeCount1(self, node):
if node == None:
return 0
if node.next == None:
return 1
return 1 + self.getSingleLinkedListNodeCount1(node.next)
1.编写一个方法,接受head节点,同时接收一个index
2. index表示是倒数第index节点
3. 先把链表从头到尾遍历,得到总的长度getLength
4. 得到size后,我们从链表的第一个开始遍历(size-index)个,就可以得到
5. 如果找到返回该节点,否则返回None
class Listnode(object):
def __init__(self,data,next=None):
self.data=data
self.next=next
def getSingleLinkedListNodeCount(self,node):
if node == None:
return 0
if node.next == None:
return 1
p = node
count = 0
while p:
count += 1
p = p.next
return count
def FindLastIndexNode(self,node,k):
length = self.getSingleLinkedListNodeCount(node)
num = length - k
if k <= 0 or k > length:
return None
p = node
while p and num >0:
p = p.next
num -= 1
return p.data
方法二:借助外力,把每个节点都保存在列表中,然后直接取列表的倒数第k个即可
class Solution:
def FindKthToTail(self, head, k):
# write code here
Node=[]
while head!=None:
Node.append(head)
head=head.next
if k>len(Node) or k<1:
return
return Node[-k]
方法三:设置一个双指针,一个快一个慢,一个先走K步,然后另一个开始走,直到快指针先走到表尾,即走了N-K步,慢指针所在的位置即为倒数第K个。
class Solution:
def FindKthToTail(self, head, k):
# write code here
slow,fast=head,head
for i in range(k):
if not fast:
return None
fast=fast.next
while fast:
slow=slow.next
fast=fast.next
return slow
总结:列表添加节点;设置双指针;