输入一个链表,输出反转后的链表。

非递归实现:

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        if pHead is None:
            return pHead
        last = None  #指向上一个节点
        while pHead:
            # 先用tmp保存pHead的下一个节点的信息,
            # 保证单链表不会因为失去pHead节点的next而就此断裂
            tmp = pHead.next
            # 保存完next,就可以让pHead的next指向last了
            pHead.next = last
            # 让last,pHead依次向后移动一个节点,继续下一次的指针反转
            last = pHead
            pHead = tmp
        return last

 

上面程序中的while循环是主要部分,主体部分代码简单,但不是很好理解,下面用图示方法,以三个链表节点为例来展示其反转过程。

  • 初始链表状态
    需要定义一个变量last指向pHead的上一个节点

反转链表[剑指offer]之python实现

    • 一次迭代之后
      x0先暂时被从链表中脱离出来,由last指向,作为反转的新链,x0反转之后会是最后一个节点,因此next指向None,pHead则指向原链的下一个节点x1。
      反转链表[剑指offer]之python实现
    • 两次迭代之后
      x1被脱离出来加入反转的新链,并插入x0之前,pHead再后移。
      反转链表[剑指offer]之python实现
    • 三次迭代之后
      反转完成,pHead指向None即结束循环,返回last即为新链表的头结点。
      反转链表[剑指offer]之python实现

递归实现:

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        if not pHead or not pHead.next:
            return pHead
        else:
            newHead = self.ReverseList(pHead.next)
            pHead.next.next=pHead
            pHead.next=None
            return newHead

 

相关文章:

  • 2021-10-25
  • 2021-08-19
  • 2022-01-10
  • 2022-12-23
  • 2022-12-23
  • 2021-12-18
  • 2021-09-12
  • 2021-05-04
猜你喜欢
  • 2021-12-27
  • 2021-06-03
  • 2022-12-23
  • 2021-08-13
  • 2021-05-16
  • 2021-12-18
  • 2021-11-06
相关资源
相似解决方案