- 非递归算法:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
pFront = None
pNode = head
while pNode:
pNext = pNode.next
pNode.next = pFront
pFront = pNode
pNode = pNext
return pFront
- 递归算法:
def reverseList(self, head):
if not head or not head.next:
return head
pre = self.reverseList(head.next)
head.next.next = head
head.next = None
return pre