Reverse a singly linked list. 翻转一个链表
第一种方法:迭代
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
pre = cur = None
if head:
pre = head
cur = head.next
pre.next = None
else:
return None
while cur:
p = cur
cur = cur.next
p.next = pre
pre = p
return pre
第二种方法:递归
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head):
return reverse(head)
def reverse(self, node, prev=None):
if not node:
return prev
n = node.next
node.next = prev
return reverse(n, node)