单链表翻转 Python 实现

循环反转单链表

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

def list_reverse(head):
if head is None or head.next is None:
return head
pre = None
cur = head
h = head
while cur:
h = cur
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return h

递归实现单链表反转

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

def recurse(head,newhead):
if head is None:
return
if head.next is None:
newhead = head
else:
newhead = recurse(head.next,newhead)
head.next.next = head
head.next = None
return newhead

This blog is under a CC BY-NC-SA 3.0 Unported License
本文链接:https://blog.suixin.kim/2018/05/15/one-way-linkedlist-reverse/