题目链接🔗:反转链表
题意:反转一个单链表。
示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
迭代法:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
pre = None
cur = head
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
思路:拿上图为例,定义一个空节点 pre,一个移动指针cur,一个存储cur下一个节点变量tmp,因为存在反转操作,所以要在反转之前把他的下个节点存起来,才能进行下一步操作
递归法:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
def recur(cur,pre):
if not cur:
return pre
res = recur(cur.next,cur)
cur.next = pre # 反转
return res
return recur(head,None)