反转单链表。
迭代法:
pFront(开始设置为None)、pNode、pNext(重点是记住下一节点,免得丢了)。
# 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
递归法:
先递归到最后一个节点,pre.next=head(反转),head.next=None(切断)。
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