题目要求:
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
这里先只做一个迭代法,利用两个指针来实现,基本思想就是用两个指针一起往后遍历来实现
# 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:
pre=None
cur=head
while cur:
nextnode=cur.next
cur.next=pre
pre=cur
cur=nextnode
return pre
博客围绕Leetcode题目,要求反转单链表,可迭代或递归实现。这里采用迭代法,利用两个指针一起往后遍历完成反转,给出了Python代码实现,定义了单链表节点类和反转链表的函数。
580

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



