反转链表
给你单链表的头节点
head
,请你反转链表,并返回反转后的链表。
Python
解一:
# 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
"""
p = ListNode(next = head)
q = ListNode(next = head)
length = 0
if head == None:
return head
while q.next != None:
q = q.next
length += 1
i = 0
while i < length-1:
temp = ListNode()
temp = p.next.next
p.next.next = q.next
q.next = p.next
p.next = temp
i += 1
head = q
return head
解二:
# 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
"""
if head == None:
return head
p = ListNode(next = head)
q = ListNode()
q = head
temp = ListNode()
temp = None
while q != None:
p = q
q = q.next
p.next = temp
temp = p
head = p
return head
解三:
# 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 reverse(p,q):
if q == None:
return p
temp = q.next
q.next = p
return reverse(q,temp)
return reverse(None,head)
笔记
-
翻转链表可以考虑使用双指针法,但是双指针之间亦有差别,例如:
- 解一中两个指针分别放在原链表的首尾端,依次将首端的链点用头插法插在尾部指针指向链点的后面,这样,当原链表中链点全部加入尾端时,就成功实现了链表的反转,新链表首节点即为q.next(注意,其实原链表的尾端可以直接当作新链表的首端的,这一原来的尾端指针q就是head了,解一中也是这样写的)
- 解二中两个指针刚开始都在首段的,它们每往后移动一位都会将原来两个链点之间的指向反转(q指针的意义是为p指针指路,防止p指针在p.next = temp后无法找到原链表后续的链点)
-
因为我采用了虚拟节点,因此需要格外注意原链表的第一个链点和原链表为None这两种情况;
-
解三的思路与解二是一样的,但是使用了递归:我们可以看出解二的过程实际上是p,temp两个指针指向链点之间指针的反转,可以用递归来处理,要注意递归时输入形参是什么(即要注意在下一次循环中p,temp对应什么),还要注意递归需要有停止的途径。