栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python操作链表的示例代码

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python操作链表的示例代码

class Node:
  def __init__(self,dataval=None):
    self.dataval=dataval
    self.nextval=None


class SlinkList:
  def __init__(self):
    self.headval=None

  # 遍历列表
  def traversal_slist(self):
    head_node=self.headval
    while head_node is not None:
      print(head_node.dataval)

      head_node=head_node.nextval


#   表头插入结点
  def head_insert(self,newdata):
    Newdata=Node(newdata)
    Newdata.nextval=self.headval
    self.headval=Newdata

  # 表尾插入结点
  def tail_insert(self,newdata):
    Newdata=Node(newdata)

    if self.headval is None:
      self.headval=Newdata
      return
    head_node = self.headval
    while head_node.nextval :
      head_node=head_node.nextval
    head_node.nextval=Newdata

#   在两个数据结点之间插入
  def middle_insert(self,middle_node,newdata):
    Newdata=Node(newdata)
    if middle_node is None:
      return
    Newdata.nextval=middle_node.nextval
    middle_node.nextval=Newdata

#   删除结点
  def remove_node(self,newdata):
    head_node=self.headval
    if head_node==None:
      return
    if head_node.dataval == newdata:
      self.headval = head_node.nextval
      head_node = None
      return
    while head_node is not None:
      prev=head_node
      head_node=head_node.nextval
      if head_node:
 if head_node.dataval==newdata:
   prev.nextval=head_node.nextval
   
   
lis=SlinkList()
lis.headval=Node('aa')
ee=Node('bb')
lis.headval.nextval=ee

lis.head_insert('cc')
lis.tail_insert('dd')
lis.middle_insert(ee,"Fri")
lis.remove_node('bb')

lis.traversal_slist()

以上就是python操作链表的示例代码的详细内容,更多关于Python链表的资料请关注考高分网其它相关文章!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/16984.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号