python实现单链表反转(经典笔试题)

0、说在前面的话

     链表结构,说难不难,说易不易,一定要亲自编程实现一下。其次就是一定要耐心,慢慢去体会其中的道道,博主一开始也是有点懵逼的,后来仔细琢磨了一下终于搞明白了,相信聪明的你也一定可以,有问题可以留言交流。

1、单链表结构

2、反转的想法

      建立三个变量,L、M、R互相赋值迭代,并建立指向关系,从而实现单链表的反转。

3、python代码实现

class Node(object):
    def __init__(self, data, next=None):
        self.val = data
        self.next = next

def fun4(head):
    if head == None:
        return None
    L,M,R = None,None,head
    while R.next != None:
        L = M
        M = R
        R = R.next
        M.next = L
    R.next = M
    return R
#测试用例
if __name__ == '__main__':
    l1 = Node(3)
    l1.next = Node(2)
    l1.next.next = Node(1)
    l1.next.next.next = Node(9)
    l = fun4(l1)
    print (l.val, l.next.val, l.next.next.val, l.next.next.next.val)

猜你喜欢

转载自blog.csdn.net/su_bao/article/details/81072849
今日推荐