算法-链表翻转

反转一个单链表。

简单直白方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class ListNode:
def __init__(self, x):
self.val = x
self.next = None


class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return head
first = None
second = head
while True:
third = second.next
second.next = first

if third is None:
break

first = second
second = third
return second

大神快速方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class ListNode:
def __init__(self, x):
self.val = x
self.next = None


class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
prev = None
while head:
curr = head
head = head.next
curr.next = prev
prev = curr

return prev