class Node(object):
def __init__(self, item, next):
self.item = item
self.next = next
class Link(object):
def __init__(self, init_list: list):
"""
初始化
"""
self._link = None
self._init_link(init_list)
self._reverse_link = None
def _init_link(self, init_list: list):
init_list.reverse()
for item in init_list:
self._link = Node(item, self._link)
@property
def list(self):
"""
将链表转换成list
:return:
"""
res = []
link = self._link
while link:
res.append(link.item)
link = link.next
return res
def clear(self):
"""
清空链表
:return:
"""
self._link = None
def delete(self, item):
"""
删除某个元素
:param item:
:return:
"""
link = self._link
prev = None
i = 0
while link:
if item == link.item:
if prev is None:
self._link = link.next
else:
prev.next = link.next
break
prev = link
link = link.next
def insert(self, item, index):
"""
向链表index位置插入一个item元素
:param item:
:param index:
:return:
"""
i = 0
if index == 0:
self._link = Node(item, self._link)
else:
if index == self.length - 1:
_index = index
else:
_index = index - 1
link = self._link
while link:
if _index == i:
link.next = Node(item, link.next)
break
i = i + 1
link = link.next
def append(self, item):
"""
向链表末尾添加一个元素
:param item:
:return:
"""
self.insert(item, self.length - 1)
def reverse(self, next=None):
"""
链表反转(递归)
:return:
"""
if next is None:
link = self._link
else:
link = next
self._reverse_link = Node(link.item, self._reverse_link)
if link.next is None:
self._link = self._reverse_link
self._reverse_link = None
return
self.reverse(link.next)
@property
def length(self):
"""
获取链表的长度
:return:
"""
return len(self.list)
def empty(self):
"""
链表是否为空
:return:
"""
if self._link is None:
return True
else:
return False
def in_link(self, item):
"""
判断元素是否在链表中
:param item:
:return:
"""
link = self._link
while link:
if item == link.item:
return True
link = link.next
return False
if __name__ == '__main__':
link = Link(['zhangbo', 'liudong', 'zhuxiang', 'suirun'])
print(link.list)
link.insert('wuxiaokang', 3)
print(link.list)
link.append('hufang')
print(link.list)
link.insert('shenming', 0)
print(link.list)
link.delete('suirun')
print(link.list)
link.reverse()
print(link.list)
链表
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 题目描述 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,...
- 1.1 题目 题号1:分别以单链表、循环链表、双向链表为例,实现线性表的建立、插入、删除、查找等基本操作。 要求:...