python单向链表的基本实现与使用方法【定义、遍历、添加、删除、查找等】

yipeiwu_com6年前Python基础

本文实例讲述了python单向链表的基本实现与使用方法。分享给大家供大家参考,具体如下:

# -*- coding:utf-8 -*-
#! python3
class Node():
  def __init__(self,item):
    #初始化这个节点,值和下一个指向
    self.item = item
    self.next = None
class SingleLinklist():
  def __init__(self):
    #初始化这个单链表的头指针为空
    self._head = None
  def length(self):
    #获取这个链表的长度
    count = 0
    cur = self._head
    while cur != None:
      count+=1
      cur = cur.next
    return count
  def is_empty(self):
    """判断是否为空"""
    return self._head == None
  def add(self,item):
    """在头部添加元素"""
    node = Node(item)
    node.next = self._head
    self._head = node
  def append(self,item):
    """在尾部添加元素"""
    cur = self._head
    node = Node(item)
    while cur != None:
      cur = cur.next
    cur.next = node
  def insert(self,pos,item):
    """在选定的位置添加元素"""
    cur = self._head
    node = Node(item)
    count = 0
    if pos <= 0:
      self.add(item)
    elif pos > (self.length()-1):
      self.append(item)
    else:
      while count < (pos -1):
        count+=1
        cur = cur.next
      node.next = cur.next
      cur.next = node
  def travel(self):
    """遍历整个链表"""
    cur = self._head
    while cur != None:
      print(cur.item,end=" ")
      cur = cur.next
    print(" ")
  def remove(self,item):
    """删除链表"""
    cur = self._head
    pre =None
    while cur != None:
      if cur.item == item:
        if not pre:
          self._head = cur.next
          break
        else:
          pre.next = cur.next
      else:
        pre = cur #
        cur = cur.next
  def search(self,item):
    """查找某个节点"""
    cur = self._head
    while cur != None:
      if cur.item == item:
        print("找到这个元素了")
        return True
      cur = cur.next
    print("抱歉没有这个元素")
    return False
singlistdemo = SingleLinklist()
singlistdemo.add(1)
singlistdemo.add(2)
singlistdemo.add(65)
singlistdemo.insert(2,77)
singlistdemo.insert(1,66)
singlistdemo.insert(0,66)
print(singlistdemo.length())
singlistdemo.travel()
singlistdemo.remove(1)
singlistdemo.travel()
singlistdemo.search(65)

运行结果:

6
66 65 66 2 77 1 

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

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

相关文章

python 搜索大文件的实例代码

如下所示: import os,os.path def getBigFile(pathname,filesize):#第一个参数为要遍历的文件夹,第二个是要找的最小文件的大小...

Python 实现两个列表里元素对应相乘的方法

方法一: 结合zip函数,使用map函数: List1 = [1,2,3,4] List2 = [5,6,7,8] List3 = map(lambda (a,b):a*b,zip(...

Python分析彩票记录并预测中奖号码过程详解

Python分析彩票记录并预测中奖号码过程详解

0 引言 上周被一则新闻震惊到了,《2454万元大奖无人认领!福彩史上第二大弃奖在广东中山产生 》,在2019年5月2日开奖的双色球中,广东中山一位彩民博中2454万元,兑奖时间截至2...

videocapture库制作python视频高速传输程序

videocapture库制作python视频高速传输程序

1,首先是视频数据[摄像头图像]的采集,通常可以使用vfw在vc或者vb下实现,这个库我用的不好,所以一直不怎么会用.现在我们用到的是python的videocapture库,这个库用起...

在Python中操作字典之clear()方法的使用

 clear()方法将删除字典中的所有项目(清空字典) 语法 以下是clear()方法的语法: dict.clear() 参数   &nbs...