# 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
# if head.next == None:
# return head
# new_head = self.reverseList(head.next)
# head.next.next = head(建立双向链表)
# head.next = None
# return new_head
#循环(头插)--利用三个变量(p一直指向头节点,r指向待头插的节点,q为中间变量)
if head ==None:
return
p = head
q = head.next
p.next = None
while q:
r = q.next
q.next = p
p = q
q = r
return p
206. 反转链表
最新推荐文章于 2021-07-14 00:19:45 发布