【题目】
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
【示例】
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
【限制】
0 <= 节点个数 <= 5000
【代码】
【Python】

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
num=[]
t=head
while t:
num.append(t.val)
t=t.next
num=num[::-1]
t=head
i=0
while t:
t.val=num[i]
i+=1
t=t.next
return head
【方法2】

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None:
return head
pre,now=head,head.next
while now:
t=now.next
now.next=pre
if pre==head:
pre.next=None
pre=now
now=t
return pre
【递归】

class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
newHead = self.reverseList(head.next)
head.next.next = head
head.next = None
return newHead
本文介绍如何使用Python实现链表反转,包括递归、迭代和传统迭代方式的代码示例,并解释了它们的工作原理。通过实例演示,帮助读者理解链表反转的基本操作。
282

被折叠的 条评论
为什么被折叠?



