【算法与数据结构相关】【LeetCode】【206 反转链表】【Python】

题目:反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

思路:用三个变量,分别代表当前节点,前一个节点和下一个节点,具体参考链表反转

代码:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return None
        cur = head            #之前在这里加了一句cur.next = None,导致错误
        nxt = head.next
        pre = None
        while nxt:
            cur.next = pre
            pre = cur
            cur = nxt
            nxt = nxt.next
        cur.next = pre
        return cur

注意,这里的cur、pre、nxt都是对原链表节点的引用,如果另cur.next == None也会改变原链表的结构!

另外一种反转的方法是递归:现在需要把A->B->C->D进行反转,可以先假设B->C->D已经反转好,已经成为了D->C->B,那么接下来要做的事情就是将D->C->B看成一个整体,让这个整体的next指向A,所以问题转化了反转B->C->D。那么,可以先假设C->D已经反转好,已经成为了D->C,那么接下来要做的事情就是将D->C看成一个整体,让这个整体的next指向B,所以问题转化了反转C->D。那么,可以先假设D(其实是D->NULL)已经反转好,已经成为了D(其实是head->D),那么接下来要做的事情就是将D(其实是head->D)看成一个整体,让这个整体的next指向C,所以问题转化了反转D。

代码:

def reverse(head):
    if head.next == None:
        return head
    new_head = reverse(head.next)
    head.next.next = head
    head.next = None
    return new_head

猜你喜欢

转载自blog.csdn.net/gq930901/article/details/81916231