zoukankan      html  css  js  c++  java
  • python实现链表中倒数第k个结点

    题目描述

    输入一个链表,输出该链表中倒数第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
            l = []
            while head != None:
                l.append(head)
                head = head.next
            if k > len(l) or k < 1:
                return
            return l[-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 or k == 0:
                return None
            pAhead = head
            pBehind = None
            for i in range(0,k-1):
                if pAhead.next != None:
                    pAhead = pAhead.next
                else:
                    return None
            pBehind = head
            while pAhead.next != None:
                pAhead = pAhead.next
                pBehind = pBehind.next
            return pBehind
    
  • 相关阅读:
    hadoop架构
    hdfs存储模型
    C语言编译过程
    linux文件类型和权限
    推荐系统效果评估
    推荐系统冷启动
    Js计算-当月每周有多少天
    3D动画
    固定边栏——淘宝滚动效果
    jquery图片轮播-插件
  • 原文地址:https://www.cnblogs.com/tianqizhi/p/9669556.html
Copyright © 2011-2022 走看看