Python函数来反转一个链表

huangapple go评论77阅读模式
英文:

Python function to reverse a linked list

问题

能否请有人帮助我看看这段代码有什么问题?

为了实现这个目标:
定义一个函数,输入一个链表的头节点,将链表反转,并输出反转后的头节点。

示例:
输入:1->2->3->4->5->NULL
输出:5->4->3->2->1->NULL

class ListNode(object):
    def __init__(self, val: int):
        self.val: int = val
        self.next: Optional[ListNode] = None

class Solution(object):
    def reverseList(self, head):
        if not head:
            return None
        l = []
        while head:
            l.append(head.val)
            head = head.next
        l = l[::-1]
        hn = ListNode(l[0]) 
        for i in range(1, len(l)):
            hn.next = ListNode(l[i])
            nnext = hn.next
            hn = nnext
        return hn

它只返回一个单一的值,如果我想要输出整个列表怎么办?
谢谢您的关注,任何与编码/概念/逻辑相关的帮助将不胜感激。

英文:

Could anyone please help me to look at what's wrong with the code here?

In order to achieve this:
Define a function that inputs the head node of a linked list, reverses the list and outputs the head node of the reversed list.

Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

class ListNode(object):
    def __init__(self, val: int):
        self.val: int = val
        self.next: Optional[ListNode] = None

class Solution(object):
    def reverseList(self, head):
        if not head:
            return None
        l = []
        while head:
            l.append(head.val)
            head = head.next
        l = l[::-1]
        hn = ListNode(l[0]) 
        for i in range(1, len(l)):
            hn.next = ListNode(l[i])
            nnext = hn.next
            hn = nnext
        return hn

It only returns a single value, what if I want it to output the whole list?
Thank you for your attention and any help with coding/concept/logic would be appreciated.

答案1

得分: 1

创建一个Python列表有点违背了使用链表的目的。你应该尽量通过操作节点之间的链接来实现这个目标。

例如:

def reverseList(head):
    tail = None
    while head:
        head.next, tail, head = tail, head, head.next
    return tail

如果你要使用Python列表,首先用节点填充它。然后将每个节点链接到列表中的前一个节点。最后,返回列表中的最后一个节点:

def reverseList(head):
    nodes = [None]
    while head:
        nodes.append(head)
        head = head.next
    for i, previous in enumerate(nodes[:-1], 1):
        nodes[i].next = previous
    return nodes[-1]
英文:

Creating a Python list kinda defeats the purpose of working with linked lists. you should try to achieve this only by manipulating links between nodes.

For example:

def reverseList(head):
    tail = None
    while head:
        head.next, tail, head = tail, head, head.next
    return tail

If you're going to use a Python list, first fill it with the nodes. Then link each node to the previous one in the list. Finally, return the last node in the list:

def reverseList(head):
    nodes = [None]
    while head:
        nodes.append(head)
        head = head.next
    for i,previous in enumerate(nodes[:-1],1):
        nodes[i].next = previous
    return nodes[-1]

答案2

得分: 0

你的代码有问题的地方在于,在创建一个新列表时,你从以下代码开始:

hn = ListNode(l[0])

但在循环内部,你通过覆盖hn失去了对第一个节点的跟踪:

hn = nnext

最后,当你return hn时,你正在引用最终创建的ListNode

英文:

What is wrong with your code is that in creating a new list you start with:

hn = ListNode(l[0])

but inside the loop you lose track of that first node by overwriting hn:

hn = nnext

Finally when you return hn you are referencing the final ListNode created.

huangapple
  • 本文由 发表于 2023年6月4日 23:30:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76401138.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定