链表中倒数第k个节点

来源:互联网 发布:淘宝申请退款到账时间 编辑:程序博客网 时间:2024/05/22 03:44

题目描述:

输入一个链表,输出链表中倒数第k个节点。

答案:

# -*- coding:utf-8 -*-# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = Noneclass 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 = Nonedef create():    head = ListNode(1)    p = head    for i in range(2,5):        p.next = ListNode(i)        p = p.next    return headdef length(head):    p = head    count = 1    while p.next!=None:        count+=1        p = p.next    return counth = create()#1234print(length(h))#4




原创粉丝点击