python linkedlist部分反转

时间:2017-09-20 18:42:08

标签: python list linked-list reverse

我在课堂上有一个链接列表,如

7,5,3,1,2,4,6,8

我想得到像

这样的输出
1,3,5,7,2,4,6,8

当我尝试使用以下反向代码时:

class Linkedlist:
def __init__(self, L = None):
...
def partlyreverse(self):
    tail = self.head
    current_node = self.head.next_node
    tail.next_node = None
    while current_node.value % 2 == 1:
        next_current_node = current_node.next_node
        current_node.next_node = tail
        tail = current_node
        current_node = next_current_node

    self.head = tail
L = Linkedlist([7,5,3,1,2,4,6,8])
L.partlyreverse()

我只能

1,3,5,7

所以我怎么能这样做?

谢谢!

2 个答案:

答案 0 :(得分:0)

你基本上需要检查列表的开头是否包含奇数或偶数!基于此你需要逆转!

>>> s
(7, 3, 5, 1, 2, 4, 6, 8)
>>> sorted(filter(lambda x:(x%2!=0 and s[0]%2!=0) or (x%2==0 and s[0]%2==0),s)) + sorted(filter(lambda x:(x%2!=0 and s[-1]%2!=0) or (x%2==0 and s[-1]%2==0),s))
[1, 3, 5, 7, 2, 4, 6, 8]

答案 1 :(得分:0)

你的问题不是100%明确:你是否试图将链表分成两半,开头是奇数整数,最后是偶数?您是否尝试对列表进行分区而不考虑值本身?

此外,必须有您未提交问题的代码...我已经最好地猜测了代码的外观。

下面的代码段会返回您想要的输出:

class Node:
    def __init__(self, value):
        self.value = value
        self.next_node = None

class Linkedlist:
    def __init__(self, L=None):
        self.head = Node(L[0])
        current = self.head
        for value in L[1:]:
            current.next_node = Node(value)
            current = current.next_node

    def partlyreverse(self):
        tail_start = self.head
        tail_end = self.head
        tail2_start = None
        tail2_end = None

        current_node = self.head.next_node

        while current_node != None:
            if current_node.value % 2 == 1:
                next_current_node = current_node.next_node
                current_node.next_node = tail_start
                tail_start = current_node
                current_node = next_current_node
            else:
                if not tail2_start:
                    tail2_start = current_node
                    tail2_end = tail2_start
                    current_node = current_node.next_node             
                else:
                    tail2_end.next_node = current_node
                    tail2_end = current_node
                    current_node = current_node.next_node 

        tail_end.next_node = tail2_start
        self.head = tail_start

L = Linkedlist([7,5,3,1,2,4,6,8])

L.partlyreverse()

def RecursivelyPrintNodes(node):
    if node != None:
        print node.value
        RecursivelyPrintNodes(node.next_node)

RecursivelyPrintNodes(L.head)

# 1,3,5,7,2,4,6,8

最后,我在你的代码中看到了你的目标,但是作为一个注释,你编写的代码将无法编译(你的类中存在缩进错误)。