Python单链表简单实现代码

yipeiwu_com5年前Python基础

本文实例讲述了Python单链表简单实现代码。分享给大家供大家参考,具体如下:

用Python模拟一下单链表,比较简单,初学者可以参考参考

#coding:utf-8
class Node(object):
  def __init__(self, data):
    self.data = data
    self.next = None
class NodeList(object):
  def __init__(self, node):
    self.head = node
    self.head.next = None
    self.end = self.head
  def add_node(self, node):
    self.end.next = node
    self.end = self.end.next
  def length(self):
    node = self.head
    count = 1
    while node.next is not None:
      count += 1
      node = node.next
    return count
  # delete node and return it's value
  def delete_node(self, index):
    if index+1 > self.length():
      raise IndexError('index out of bounds')
    i = 0
    node = self.head
    while True:
      if i==index-1:
        break
      node = node.next
      i += 1
    tmp_node = node.next
    node.next = node.next.next
    return tmp_node.data
  def show(self):
    node = self.head
    node_str = ''
    while node is not None:
      if node.next is not None:
        node_str += str(node.data) + '->'
      else:
        node_str += str(node.data)
      node = node.next
    print node_str
  # Modify the original position value and return the old value
  def change(self, index, data):
    if index+1 > self.length():
      raise IndexError('index out of bounds')
    i = 0
    node = self.head
    while True:
      if i == index:
        break
      node = node.next
      i += 1
    tmp_data = node.data
    node.data = data
    return tmp_data
  # To find the location of index value
  def find(self, index):
    if index+1 > self.length():
      raise IndexError('index out of bounds')
    i = 0
    node = self.head
    while True:
      if i == index:
        break
      node = node.next
      i += 1
    return node.data
#test case
n1 = Node(0)
n2 = Node(1)
n3 = Node(2)
n4 = Node(3)
n5 = Node(4)
node_list = NodeList(n1)
node_list.add_node(n2)
node_list.add_node(n3)
node_list.add_node(n4)
node_list.add_node(n5)
#node = node_list.delete_node(3)
#print node
#d = node_list.change(0,88)
data = node_list.find(5)
print data
node_list.show()

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

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

相关文章

Python中浅拷贝copy与深拷贝deepcopy的简单理解

以下是个人对Python深浅拷贝的通俗解释,易于绕开复杂的Python数据结构存储来进行理解! 高级语言中变量是对内存及其地址的抽象,Python的一切变量都是对象。 变量的存...

在Python中如何传递任意数量的实参的示例代码

1 用法 在定义函数时,加上这样一个形参 "*形参名",就可以传递任意数量的实参啦: def make_tags(* tags): '''为书本打标签''' print('标...

python topN 取最大的N个数或最小的N个数方法

如下所示: import numpy as np a = np.array([1,4,3,5,2]) b = np.argsort(a) print(b) print结果[0 4...

对Python w和w+权限的区别详解

今日上课,有位同学问到:w和w+有何区别呢。 说实话,我们经常只是用一种权限,没用在意之间的区别,实际上,w+具有可读可写权限,而w只有可写权限。 下面上代码: fd=open(...

python实现点击按钮修改数据的方法

使用JSON获取前端数据,转成JSON,传递到后端,然后对数据库做修改。 前端代码 <div style="padding: 10px;"> <button c...