python实现获取单向链表倒数第k个结点的值示例

yipeiwu_com6年前Python基础

本文实例讲述了python实现获取单向链表倒数第k个结点的值。分享给大家供大家参考,具体如下:

#初始化链表的结点
class Node():
  def __init__(self,item):
    self.item = item
    self.next = None
#传入头结点,获取整个链表的长度
def length(headNode):
  if headNode == None:
    return None
  count = 0
  currentNode =headNode
  #尝试了一下带有环的链表,计算长度是否会死循环,确实如此,故加上了count限制 = =||
  while currentNode != None and count <=1000:
    count+=1
    currentNode = currentNode.next
  return count
#获取倒数第K个结点的值,传入头结点和k值
def findrKnode(head,k):
  if head == None:
    return None
  #如果长度小于倒数第K个值,则返回通知没有这么长
  elif length(head)<k:
    print("链表长度没有倒数第"+str(k)+"数")
    return None
  else:
    #设置两个针,一个快,一个慢,都指向头结点
    fastPr = head
    lowPr = head
    count = 0
    #让fastPr先走k个长度
    while fastPr!=None and count<k:
      count+=1
      fastPr = fastPr.next
    #此时fastPr和lowPr同速前进,当fastPr走到尾部,lowPr此处的值正好为倒数的k值
    while fastPr !=None:
      fastPr = fastPr.next
      lowPr = lowPr.next
    return lowPr
if __name__ == "__main__":
  node1 = Node(1)
  node2 = Node(2)
  node3 = Node(3)
  node4 = Node(4)
  node5 = Node(5)
  node6 = Node(6)
  node7 = Node(7)
  node8 = Node(8)
  node9 = Node(9)
  node10 = Node(10)
  node1.next = node2
  node2.next = node3
  node3.next = node4
  node4.next = node5
  node5.next = node6
  node6.next = node7
  node7.next = node8
  node8.next = node9
  node9.next = node10
  print(findrKnode(node1,5).item)

运行结果:

6

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python3实现简单可学习的手写体识别(实例讲解)

Python3实现简单可学习的手写体识别(实例讲解)

1.前言 版本:Python3.6.1 + PyQt5 + SQL Server 2012 以前一直觉得,机器学习、手写体识别这种程序都是很高大上很难的,直到偶然看到了这个视频,听了老师...

Python yield使用方法示例

1. iterator叠代器最简单例子应该是数组下标了,且看下面的c++代码: 复制代码 代码如下:int array[10];for ( int i = 0; i < 10; i...

Python正则表达式匹配HTML页面编码

html页面一般都会指定一个编码,如何获取到是处理html页面的第一步,因为错误的编码必然带来后面处理的问题。这里我用python的正则表达式写了个: import re a =...

python使用Turtle库绘制动态钟表

python使用Turtle库绘制动态钟表

Python函数库众多,而且在不断更新,所以学习这些函数库最有效的方法,就是阅读Python官方文档。同时借助Google和百度。 本文介绍的turtle库对应的官方文档地址 绘制动态钟...

详解python的数字类型变量与其方法

前言 python数据类型是不允许改变的,这就意味着如果改变 Number 数据类型的值,将重新分配内存空间。下面话不多说,来看看详细的介绍吧。 以下实例在变量赋值时 Number 对...