编程实现单链表的逆转函数

编程实现单链表的逆转函数

http://www.nowcoder.com/questionTerminal/33e343e6d5df40bc9b3a26b01c82a718

编程实现单链表的逆转函数

实现单链表的逆转函数,输入一个链表,反转链表后,返回翻转之后的链表。

同从尾到头打印链表

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

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, head):
        if not head :
            return []
        cur = head.next
        head.next = None #magic?#最后一个节点搞成空,不加死循环!
        while cur:
            nextNode = cur.next
            cur.next = head  #
            head = cur
            cur = nextNode
        cur = head 
        res = []
        while  cur:
            res.append(cur.val)
            cur = cur.next

        return res
全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务