【发布时间】:2021-04-21 09:28:16
【问题描述】:
我们的任务是执行以下代码。
给你一个包含 N 个整数的链表。您要对列表执行以下反向操作:
选择列表中仅包含偶数的所有子部分。例如,如果列表为 {1,2,8,9,12,16},则选定的子部分将为 {2,8}、{12,16}。
反转选定的子部分,例如 {8,2} 和 {16,12}。
列表现在应该是 {1,8,2,9,16,12}。
问题是它没有创建子列表并像[2, 8, 12, 16]那样给我输出,但我想要像{2,8}, {12,16}这样的输出。
下面是我的代码:
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def append_value(self, x):
if not isinstance(x, Node):
x = Node(x)
if self.head is None:
self.head = x
else:
self.tail.next = x
self.tail = x
def reverse_list_recursive(self, current, previous):
if self.head is None:
return
elif current.next is None:
self.tail = self.head
current.next = previous
self.head = current
else:
next = current.next
current.next = previous
self.reverse_list_recursive(next, current)
def is_empty(self):
return self.head is None
def __str__(self):
to_print = ''
current = self.head
while current:
to_print += f'{current.data}->'
current = current.next
if to_print:
return f'[{to_print[:-2]}]'
return '[]'
这是我的功能:
def reverse_sub_parts(self):
sublist_list = list()
current = self.head
while current:
if current.data % 2 == 0:
sublist_list.append(current.data)
current = current.next
print(sublist_list)
my_list = LinkedList()
my_list.append_value(1)
my_list.append_value(2)
my_list.append_value(8)
my_list.append_value(9)
my_list.append_value(12)
my_list.append_value(16)
my_list.reverse_sub_parts()
【问题讨论】:
标签: python data-structures linked-list