#!/usr/bin/env python
class ListNode:
def __init__(self, value=0, next=None):
self.val = value
self.next = next
def create_list(values):
head = None
for value in values[::-1]:
head = ListNode(value,head)
return head
def create_list2(values):
head = None
pre = None
for i in range(0,len(values),1):
cur = ListNode(values[i],None)
if pre is not None:
pre.next = cur
pre = cur
else:
head = cur
pre = cur
return head
def print_list(head):
val = ""
cur = head
while cur is not None:
val = val + str(cur.val) + '->'
cur = cur.next
val = val + 'Null'
print(val)
def reverse_list(head):
if head is None or head.next is None:
return head
new_head = reverse_list(head.next)
head.next.next = head
head.next = None
return new_head
def reverse_list2(head):
pre = None
cur = head
next_node = None
while cur is not None:
next_node = cur.next
cur.next = pre
pre = cur
cur = next_node
return pre
if __name__ == '__main__':
values = [1,2,3,4,5]
list = create_list2(values)
print_list(list)
print_list(reverse_list(list))
list2 = create_list2(values)
# print_list(list2)
print_list(reverse_list2(list2))
链表反转
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...