zoukankan      html  css  js  c++  java
  • 反转链表[剑指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 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的上一个节点

    这里写图片描述

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

    递归实现:

    # -*- 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
    
  • 相关阅读:
    jsack
    生产BackPressure 的代码
    org.apache.flink.runtime.entrypoint.StandaloneSessionClusterEntrypoint
    https://www.callicoder.com/java-8-completablefuture-tutorial/
    microservices kubernetes
    flink metrics
    numRecordsIn 在哪里实现?
    flink Job提交过程
    https://jzh.12333sh.gov.cn/jzh/
    blocking
  • 原文地址:https://www.cnblogs.com/tianqizhi/p/9673894.html
Copyright © 2011-2022 走看看