翻转列表 python

太难啦,!!!昨天晚上,不,昨天上午开始看,一直到今天下午,,,终于在参考别人图解的基础上,调出来了!!感谢这个图

翻转列表 python_第1张图片

下面是我的代码,和参考答案大同小异吧,包括了链表定义和赋值

class ListNode:
    def __init__(self, x=None, next=None):
        self.val = x
        self.next = None

l1 = ListNode(1)
head = l1
for i in range(2, 10):
    head.next = ListNode(i)
    head = head.next
head = l1

def change(pre, cur):
    if cur == None: return pre
    cu = cur.next
    cur.next = pre
    return change(cur, cu)

k = 2
dunmmy = ListNode(0)
pre = dunmmy
end = dunmmy
dunmmy.next = head
while (end.next != None):
    start = pre.next
    for i in range(k):
        end = end.next
        if end == None: break
    if end == None: break
    next1 = end.next
    end.next = None
    pre.next = change(end.next, start)
    start.next = next1
    pre = start
    end = pre
head = dunmmy.next
while head != None:
    print(head.val)
    head = head.next

 

你可能感兴趣的:(加油刷题,链表,数据结构)