leetcode 206. 反转链表(python)

在这里插入图片描述
题解:
本题有两种实现方法,分别是迭代法和递归法;

方法一:迭代法:
利用双指针进行实现
两个指针分别是pre, curr;
再加一个临时变量temp;

  1. pre初始化为None;curr初始化为head;
  2. 然后令temp=curr.next(保存下一个结点,以便后面使用);
  3. curr.next = pre(建立当前结点和它前面结点之间的连接关系);
  4. pre = curr(往前移动pre);
  5. curr = temp(往前移动curr);
  6. 最后curr为None,返回pre即为最后一个结点。
    图解如下所示:
    第一次迭代:
    在这里插入图片描述
    第二次迭代:
    在这里插入图片描述
    代码如下:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:

    def reverseList(self, head):

    	pre = ListNode(None)
    	curr = head
    	tmp = ListNode(None)

    	while curr:

    		tmp = curr.next

    		curr.next = pre

    		pre = curr

    		curr = tmp




    	return pre

方法二:递归法

(结合代码来看更容易理解)
对于一个给定的链表,我们首先需要遍历到链表的尾端,例如对于[1,2,3,4,5],递归遍历到最后返回5;
即当前的head值为5,head.next 为None,head.next.next为None所指向的结点, head.next.next赋值为结点5(head.next.next = head),实现了链表方向的反向连接,然后进行递归返回; 返回后cur为5,head就变为了4,此时head.next = 5, head.next.next就是结点5的指针指向的结点;因此我们把head.next.next 赋值为head,就实现了结点5到结点4的反向连接。

递归过程如下所示:
1–>2–>3–>4–>5–>None

  1. 先遍历到链表的末尾,
    head = 1 … head.next=2
    head = 2 … head.next=3
    head = 3 … head.next=4
    head = 4 … head.next=5
    head = 5 … head.next= None
  2. 递归返回一
    此时遇到递归终止条件,进行返回,返回当前的head 为5,即cur=5;此时head.next.next为Null指向的结点我们赋值为head,首先了null指向head结点(5)的效果。
    如下图所示:
    在这里插入图片描述
  3. 递归返回二
    cur值为5,head此时为4,head.next为结点5, 因此head.next.next = head就实现了下述效果
    在这里插入图片描述
    为了防止出现环路,我们需要设置head.next = None。

后面的递归返回如上述一次进行,最后head为1。

代码如下:

class Solution:

    def reverseList(self, head):

    	if head == None or head.next == None:
    		return head

    	cur = reverseList(head.next)

    	head.next.next = head
    	head.next = None

    	return cur
发布了100 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/cy_believ/article/details/104626211