1 设置两个指针,记录当前结点和上一结点:
# Definition for 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
"""
if head == None:
return head
p = head
n = head.next
p.next = None
while n:
t = n.next
n.next = p
p = n
n = t
return p
2 设置一个中间结点,存储每一步结点的上一个结点地址:
# Definition for 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
"""
tmp = ListNode(0)
while head:
n = head.next
head.next = tmp.next
tmp.next = head
head = n
return head
如果用递归的方式:
# Definition for 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
"""
return self.reverseNode(head, None)
def reverseNode(self, head, before):
if head == None:
return before
n = head.next
head.next = before
return self.reverseNode(n, head)