链表翻转

给定单向链表,返回翻转后的链表

# coding: utf-8
# @author zhenzong
# @date 2018-05-21 11:07


class Node(object):

    def __init__(self, value, next_node):
        self.value = value
        self.next_node = next_node

    def __str__(self):
        return str(self.value)

    __repr__ = __str__


def revert_list(head):
    if not head:
        return None
    new_head, iter_node = head, head.next_node
    head.next_node = None
    while iter_node:
        tmp = iter_node.next_node
        iter_node.next_node = new_head
        new_head = iter_node
        iter_node = tmp
    return new_head


def list_to_str(_node):
    if not _node:
        return ''
    ret = str(_node)
    tmp = _node.next_node
    while tmp:
        ret = '%s,%s' % (ret, tmp)
        tmp = tmp.next_node
    return ret


def test(length_array):
    for length in length_array:
        node = None
        for i in range(length, 0, -1):
            node = Node(i, node)
        print 'length: %s, list: %s, revert_list: %s' % (length, list_to_str(node), list_to_str(revert_list(node)))


test([1, 5, 10])

# 输出
# length: 1, list: 1, revert_list: 1
# length: 5, list: 1,2,3,4,5, revert_list: 5,4,3,2,1
# length: 10, list: 1,2,3,4,5,6,7,8,9,10, revert_list: 10,9,8,7,6,5,4,3,2,1

你可能感兴趣的:(链表翻转)