单链表

单链表数据结构实现
# 定义节点
class Node():
def __init__(self,item):
self.item=item
self.next=None
# 单链表实现
class SingleLinkList():
# 定义头节点
def __init__(self,node=None):
self.__head=node
# 判断链表是否为空
def is_empty(self):
return self.__head is None
# 链表长度
def length(self):
cur=self.__head
count=0
while cur is not None:
count+=1
cur=cur.next
return count
# 循环链表
def travel(self):
cur=self.__head
while cur is not None:
print(cur.item,end='')
cur=cur.next
print('')
# 搜索节点
def search(self,item):
cur=self.__head
while cur is not None:
if cur.item==item:
return True
cur=cur.next
return False
# 头部增加节点
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 is not None:
cur=cur.next
cur.next=node
# 指定位置插入
def insert(self,pos,item):
node=Node(item)
if pos<=0:
self.add(item)
elif pos>=self.length():
self.append(item)
else:
cur=self.__head
count=0
while count<(pos-1):
cur=cur.next
count+=1
node.next=cur.next
cur.next=node
# 删除节点
def remove(self,item):
cur=self.__head
pre=None
while cur is not None:
if cur.item==item:
if cur==self.__head:
self.__head=cur.next
else:
pre.next=cur.next
return
pre=cur
cur=cur.next
if __name__ == '__main__':
ll=SingleLinkList()
for i in range(2):
ll.append(i)
print(ll.length())
ll.travel()
ll.insert(5,7)
ll.travel()
ll.remove(4)
ll.travel()









转载于:https://www.cnblogs.com/zhangweijie01/p/10229828.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值