python---链表反转

"""
Definition of ListNode

class ListNode(object):

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


class Solution:
    """
    @param: node: n
    @return: The new head of reversed linked list.
    """

    #最后的返回结点一定是元链表的最后一个尾结点,判定尾结点的方法
    #就是结点的下一位为None,然后每次在翻转的时候需要先存储后一位,
    #然后当前指向前一节点,由于翻转后原数组的第一位的下一位是None
    #所以最开始的时候pre前结点设置为None
    def reverse(self, node):
        # write your code here
        res = None
        pre = None
        cur = node
        while cur:
            cur_next = cur.next
            cur.next  = pre
            pre = cur
            if not cur_next:
                res = cur

            cur = cur_next
        return res:

猜你喜欢

转载自blog.csdn.net/hotpotbo/article/details/78518822