题目描述:
输入一个链表,输出链表中倒数第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 head!=None:
p = head
count = 1
while p.next!=None:
count+=1
p = p.next
if k<=count:
q = head
for i in range(count-k):
q = q.next
return q
else:
return None
else:
return None
补充:创建一个链表,并计算列表长度
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def create():
head = ListNode(1)
p = head
for i in range(2,5):
p.next = ListNode(i)
p = p.next
return head
def length(head):
p = head
count = 1
while p.next!=None:
count+=1
p = p.next
return count
h = create()#1234
print(length(h))#4