反转链表的后半部分

Reversing second half of a linked list

我有一个链表定义如下:

1 -> 2 -> 3 -> 4 -> 5 -> null

目标是将后半部分反转为单独的链表;

预期输出:5 -> 4 -> 空

这是我在链表class中为此目的写的两个方法;

 class SLL:   

    def reverse(self):
        prev = None
        curr = self.head
        while curr is not None:
            temp = curr.get_next()
            curr.set_next(prev)
            prev = curr
            curr = temp
    
        self.head = prev
        return self.head




    def second_half(self):
        fast = self.head
        slow = self.head
   # fast pointer moves twice as fast as compared to slow pointer

        while fast is not None and fast.get_next() is not None:
            fast = fast.get_next().get_next()
            slow = slow.get_next()
        
        temp = slow.get_next()
        slow.set_next(None)
        temp = self.reverse(temp)
        return temp

但是当我们调用上面的 reverse 方法时,参数为 temp,我们得到以下错误消息;

TypeError: reverse() takes 1 positional argument but 2 were given

我能否获得一些帮助来纠正此错误并获得所需的输出?谢谢

The goal is to reverse second half as a separate linked list;

这意味着结果应该是 SLL 的实例。这意味着您应该在某个地方通过调用 SLL.

创建新的链表

所以我建议按如下方式更改该功能:

    def second_half(self):
        fast = self.head
        slow = self.head

        while fast is not None and fast.get_next() is not None:
            fast = fast.get_next().get_next()
            slow = slow.get_next()
        
        temp = slow.get_next()
        slow.set_next(None)
        
        # changed code below:
        newlist = SSL()
        newlist.head = temp; 
        newlist.reverse()
        return newlist