链表02-反转链表

翻转链表——双指针解法

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

例子 : 1->2->3->4 反转后 4->3->2->1

这题的重点就是用一个快慢指针,两个指针一前一后将相邻节点改变指向。

稍微需要注意的事情就是 翻转过程中指针传递的先后顺序和引入中间变量temp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 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):
pre=None # 慢指针
current=head # 快指针


"""
代码块也没什么讲的 都是细节的问题
脑子里快慢指针的操作要清晰
其实就是cur连pre 然后两个指针走一步 继续连 直到结束
"""

while current:
temp=current.next # 设置中间变量方便cur继续前进
current.next=pre
pre=current
current=temp
return pre

翻转链表——递归解法

都说递归是算法能力的试金石 好好理解 别偷懒

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 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):
return self.reverse(head,None)
def reverse(self,cur,pre):
if cur==None:
return pre
temp=cur.next
cur.next=pre
return self.reverse(temp,cur)