一.题目:
反转链表
二.解题思路:
非递归法:
# 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 not head or not head.next:
return head
pre = head
cur = head.next
while cur:
cur.next,pre,cur = pre,cur,cur.next
head.next = None #head节点的next需要设置
return pre
递归法:
# 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
"""
def dfs(head,pre):
if not head:
return pre
tmp = head.next
head.next = pre
return dfs(tmp,head)
return dfs(head,None)