首先从列表开始,我应该做LinkedList并将元素放入其中(我就是这么做的)。从该列表中,我必须将所有非字符串元素(整数)移动到另一个LinkedList并打印它们
初始化:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList(object):
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def append(self,new_data):
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
last = self.head
while(last.next):
last = last.next
last.next = new_node
def Lista(lista):
linked = LinkedList()
for element in lista:
linked.append(element)
return linked
打印函数和将元素移动到另一个linkedlist的函数(izdvoji):
def ispis(self):
temp = self.head
while (temp):
print (temp.data)
temp = temp.next
print("------")
def izdvoji(self):
linked = LinkedList()
temp = self.head
while(temp):
if isinstance (temp.data, str):
linked.append(temp.data)
temp = temp.next //edited
else:
temp = temp.next
if __name__ == '__main__':
L = Lista([33, "asp","oop1",5,21,"python",2,"c++"])
ispis(izdvoji(L))
ispis(L)
结果必须是:
ASP、OOP1、Python、C++ +P>
33,5,21,2
抱歉,代码太长,但我想让你看看
编辑功能:
def izdvoji(linkedLista):
linked = LinkedList()
temp = linkedLista.head
while(temp != None):
if isinstance (temp.data, str):
linked.append(temp.data)
temp = temp.next
temp = linkedLista.head
while(temp != None):
if temp == linkedLista.head and isinstance (temp.data, str):
linkedLista.head = temp.next
print(temp.data)
if temp.next != None and isinstance (temp.next.data, str):
temp.next = temp.next.next
temp = temp.next
return linked
输出:
ASP、OOP1、Python、C++、
33,1,5,21,2,
print函数接受默认为
"\n"
的end
参数。您可以使用", "
打印列表要将节点从一个列表移动到另一个列表,需要执行两个步骤
您没有一个delete方法来处理这个问题,所以我必须自己编写delete方法
链表的删除方法
输出:
就复制而言。如果条件为true,则忘记更新临时值。从技术上讲,这里也不需要其他东西。移动未执行的元素后,还需要返回列表
输出:
主代码:
注意:按照约定,self仅用于引用类的属性和方法
izdvoji
和ispis
不是类方法。所以在这里使用self是没有意义的相关问题 更多 >
编程相关推荐