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),或者用向量,时间开销成本更低。