浅谈Python单向链表的实现


Posted in Python onDecember 24, 2015

链表由一系列不必在内存中相连的结构构成,这些对象按线性顺序排序。每个结构含有表元素和指向后继元素的指针。最后一个单元的指针指向NULL。为了方便链表的删除与插入操作,可以为链表添加一个表头。

浅谈Python单向链表的实现

删除操作可以通过修改一个指针来实现。

浅谈Python单向链表的实现

插入操作需要执行两次指针调整。

浅谈Python单向链表的实现

1. 单向链表的实现

1.1 Node实现

    每个Node分为两部分。一部分含有链表的元素,可以称为数据域;另一部分为一指针,指向下一个Node。

class Node():
  __slots__=['_item','_next']  #限定Node实例的属性
  def __init__(self,item):
    self._item=item
    self._next=None   #Node的指针部分默认指向None
  def getItem(self):
    return self._item
  def getNext(self):
    return self._next
  def setItem(self,newitem):
    self._item=newitem
  def setNext(self,newnext):
    self._next=newnext

1.2 SinglelinkedList的实现

class SingleLinkedList(): 
  def __init__(self):
    self._head=None  #初始化链表为空表
    self._size=0

1.3 检测链表是否为空

def isEmpty(self):
  return self._head==None

1.4 add在链表前端添加元素

def add(self,item):
  temp=Node(item)
  temp.setNext(self._head)
  self._head=temp

1.5 append在链表尾部添加元素

def append(self,item):
  temp=Node(item)
  if self.isEmpty():
    self._head=temp  #若为空表,将添加的元素设为第一个元素
  else:
    current=self._head
    while current.getNext()!=None:
      current=current.getNext()  #遍历链表
    current.setNext(temp)  #此时current为链表最后的元素

1.6 search检索元素是否在链表中

def search(self,item):
  current=self._head
  founditem=False
  while current!=None and not founditem:
    if current.getItem()==item:
      founditem=True
    else:
      current=current.getNext()
  return founditem

1.7 index索引元素在链表中的位置

def index(self,item):
  current=self._head
  count=0
  found=None
  while current!=None and not found:
    count+=1
    if current.getItem()==item:
      found=True
    else:
      current=current.getNext()
  if found:
    return count
  else:
    raise ValueError,'%s is not in linkedlist'%item

1.8 remove删除链表中的某项元素

def remove(self,item):
  current=self._head
  pre=None
  while current!=None:
    if current.getItem()==item:
      if not pre:
        self._head=current.getNext()
      else:
        pre.setNext(current.getNext())
      break
    else:
      pre=current
      current=current.getNext()

1.9 insert链表中插入元素

def insert(self,pos,item):
  if pos<=1:
    self.add(item)
  elif pos>self.size():
    self.append(item)
  else:
    temp=Node(item)
    count=1
    pre=None
    current=self._head
    while count<pos:
      count+=1
      pre=current
      current=current.getNext()
    pre.setNext(temp)
    temp.setNext(current)

全部代码

class Node():
  __slots__=['_item','_next']
  def __init__(self,item):
    self._item=item
    self._next=None
  def getItem(self):
    return self._item
  def getNext(self):
    return self._next
  def setItem(self,newitem):
    self._item=newitem
  def setNext(self,newnext):
    self._next=newnext
     
class SingleLinkedList(): 
  def __init__(self):
    self._head=None #初始化为空链表
  def isEmpty(self):
    return self._head==None
  def size(self):
    current=self._head
    count=0
    while current!=None:
      count+=1
      current=current.getNext()
    return count
  def travel(self):
    current=self._head
    while current!=None:
      print current.getItem()
      current=current.getNext()
  def add(self,item):
    temp=Node(item)
    temp.setNext(self._head)
    self._head=temp
 
  def append(self,item):
    temp=Node(item)
    if self.isEmpty():
      self._head=temp  #若为空表,将添加的元素设为第一个元素
    else:
      current=self._head
      while current.getNext()!=None:
        current=current.getNext()  #遍历链表
      current.setNext(temp)  #此时current为链表最后的元素
  def search(self,item):
    current=self._head
    founditem=False
    while current!=None and not founditem:
      if current.getItem()==item:
        founditem=True
      else:
        current=current.getNext()
    return founditem
  def index(self,item):
    current=self._head
    count=0
    found=None
    while current!=None and not found:
      count+=1
      if current.getItem()==item:
        found=True
      else:
        current=current.getNext()
    if found:
      return count
    else:
      raise ValueError,'%s is not in linkedlist'%item       
  def remove(self,item):
    current=self._head
    pre=None
    while current!=None:
      if current.getItem()==item:
        if not pre:
          self._head=current.getNext()
        else:
          pre.setNext(current.getNext())
        break
      else:
        pre=current
        current=current.getNext()           
  def insert(self,pos,item):
    if pos<=1:
      self.add(item)
    elif pos>self.size():
      self.append(item)
    else:
      temp=Node(item)
      count=1
      pre=None
      current=self._head
      while count<pos:
        count+=1
        pre=current
        current=current.getNext()
      pre.setNext(temp)
      temp.setNext(current)
 
if __name__=='__main__':
  a=SingleLinkedList()
  for i in range(1,10):
    a.append(i)
  print a.size()
  a.travel()
  print a.search(6)
  print a.index(5)
  a.remove(4)
  a.travel()
  a.insert(4,100)
  a.travel()
Python 相关文章推荐
python调用shell的方法
Nov 20 Python
python执行子进程实现进程间通信的方法
Jun 02 Python
Python3安装Pymongo详细步骤
May 26 Python
Python用Pillow(PIL)进行简单的图像操作方法
Jul 07 Python
Tensorflow之构建自己的图片数据集TFrecords的方法
Feb 07 Python
python3中获取文件当前绝对路径的两种方法
Apr 26 Python
Python标准库使用OrderedDict类的实例讲解
Feb 14 Python
这可能是最好玩的python GUI入门实例(推荐)
Jul 19 Python
利用python生成照片墙的示例代码
Apr 09 Python
pandas读取csv文件提示不存在的解决方法及原因分析
Apr 21 Python
Python基于QQ邮箱实现SSL发送
Apr 26 Python
Cpython解释器中的GIL全局解释器锁
Nov 09 Python
Python使用面向对象方式创建线程实现12306售票系统
Dec 24 #Python
安装ElasticSearch搜索工具并配置Python驱动的方法
Dec 22 #Python
Python生成随机验证码的两种方法
Dec 22 #Python
基于python实现微信模板消息
Dec 21 #Python
python如何实现远程控制电脑(结合微信)
Dec 21 #Python
python从入门到精通(DAY 3)
Dec 20 #Python
python从入门到精通(DAY 2)
Dec 20 #Python
You might like
php+ajax实现的点击浏览量加1
2015/04/16 PHP
CI框架扩展系统核心类的方法分析
2016/05/23 PHP
Yii2 rbac权限控制之rule教程详解
2016/06/23 PHP
PHP执行shell脚本运行程序不产生core文件的方法
2016/12/28 PHP
Javascript模板技术
2007/04/27 Javascript
JavaScript 拖拉缩放效果
2008/12/10 Javascript
js sort 二维数组排序的用法小结
2014/01/24 Javascript
Bootstrap 粘页脚效果
2016/03/28 Javascript
即将发布的jQuery 3 有哪些新特性
2016/04/14 Javascript
前端jquery部分很精彩
2016/05/03 Javascript
JavaScript的Backbone.js框架环境搭建及Hellow world示例
2016/05/07 Javascript
常用js,css文件统一加载方法(推荐) 并在加载之后调用回调函数
2016/09/23 Javascript
使用Angular.js开发的注意事项
2016/10/19 Javascript
微信小程序  modal详解及实例代码
2016/11/09 Javascript
VUE使用vuex解决模块间传值问题的方法
2017/06/01 Javascript
Node.js中的不安全跳转如何防御详解
2018/10/21 Javascript
在Vue项目中取消ESLint代码检测的步骤讲解
2019/01/27 Javascript
微信小程序 云开发模糊查询实现解析
2019/09/02 Javascript
Element中Slider滑块的具体使用
2020/07/29 Javascript
关于Python如何避免循环导入问题详解
2017/09/14 Python
python docx 中文字体设置的操作方法
2018/05/08 Python
详解如何设置Python环境变量?
2019/05/13 Python
Python 仅获取响应头, 不获取实体的实例
2019/08/21 Python
Django stark组件使用及原理详解
2019/08/22 Python
Django后端发送小程序微信模板消息示例(服务通知)
2019/12/17 Python
Django如何使用asyncio协程和ThreadPoolExecutor多线程
2020/10/12 Python
appium+python自动化配置(adk、jdk、node.js)
2020/11/17 Python
国外最大的眼镜网站:Coastal
2017/08/09 全球购物
DHC美国官网:日本通信销售第一的化妆品品牌
2017/11/12 全球购物
策划创业计划书
2014/02/06 职场文书
个人作风建设自查报告
2014/10/22 职场文书
2014年煤矿工作总结
2014/11/24 职场文书
高中生个性发展自我评价
2015/03/09 职场文书
请病假条范文
2015/08/17 职场文书
企业版Windows 11有哪些新功能? Win11适用于企业的功能介绍
2021/11/21 数码科技
用Python仅20行代码编写一个简单的端口扫描器
2022/04/08 Python