python删除链表满足pred的元素_python与算法:单链表剖分函数(对链表的元素可以按照是否满足特定功能切分为两个新的链表)...

def funct(x):

if x%2==0:

return True

else:

return False

def partition(lst,pred):

satisfy_list=LList()

unsatisfy_list=LList()

p=lst._head

# lst里面有元素

while p.next is not None:

elem=p.elem

# 如果满足条件,加入到

if pred(elem):

if satisfy_list._head is None:

satisfy_list._head=LNode(elem)

q=satisfy_list._head

while q.next is not None:

q=q.next

q.next=LNode(elem)

else:

if unsatisfy_list._head is None:

unsatisfy_list._head=LNode(elem)

r=unsatisfy_list._head

while r.next is not None:

r=r.next

r.next=LNode(elem)

p=p.next

satisfy_list.printall()

unsatisfy_list.printall()

return satisfy_list,unsatisfy_list

# 测试,程序需要继承前文的LList类

# 创造一个链表加入元素

m1=LList()

for i in range(20):

m1.append(i)

m2=LList()

for i in range(11,20):

m2.append(i)

print('m1',m1.printall())

print('m2',m2.printall())

x,y=partition(m2,funct)

print(m2.printall())

print(x.printall())

print(y.printall())

从算法的效率上来看,实现这个功能用顺序表或者双向链表效率会更高,比单链表会高很多,目前的单链表时间开销应该是O(n^2),使用python的list可以实现O(n),或者用向量,时间开销成本更低。

bfa3203bbac14d76c03afedc92631e32.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值