python实现单单链表
2021-06-17 07:04
标签:pycha 删除 file param python实现 odi 记录 time pre python实现单单链表 标签:pycha 删除 file param python实现 odi 记录 time pre 原文地址:https://www.cnblogs.com/c-x-a/p/9721592.html# -*- coding: utf-8 -*-
# @Time : 2018/9/28 22:09
# @Author : cxa
# @File : node.py
# @Software: PyCharm
# 单向列表
# 数据元素区,下一个结点的链接区
# 尾节点指向的结点为空。
"""
表元素域 下一结点链接域
"""
class Node:
# 结点类
def __init__(self, elem):
self.elem = elem
self.next = None
class SingLinkList(object):
# 链表类
def __init__(self, node=None):
self.__head = node
def is_empty(self):
"""列表是否为空"""
return self.__head == None
def length(self):
"""结点的数目,到尾节点截止。需要一个游标、来记录当前的位置"""
cur = self.__head
"""count记录数量,如果空链表也可以正确处理"""
count = 0
"""开始游标移动"""
while cur:
count += 1
cur = cur.next
return count
def travel(self):
"""遍历列表"""
cur = self.__head
while cur:
print("当前的结点", cur.elem, end=‘‘)
cur = cur.next
def add(self, item):
"""从头部添加,头插法"""
node = Node(item)
node.next = self.__head
self.__head = node
def append(self, item):
"""从尾部添加,尾插法"""
node = Node(item)
if self.is_empty():
self.__head = node
else:
cur = self.__head
while cur.next:
cur = cur.next
cur.next = node
def insert(self, pos, item):
node = Node(item)
‘‘‘
从指定位置添加
:param pos: 从0开始
:param item:
:return:
‘‘‘
if pos self.length(item) - 1:
self.append(item)
else:
pre = self.__head # pre指前一个对象
count = 0
while count