zoukankan      html  css  js  c++  java
  • 递归

    什么是递归呢?

      一个函数在内部调用函数自身

      每次调用都将问题转化为子问题来执行

    废话不多说, 上实例:

    • 以相反的顺序打印字符串
    def revers(index, str):
        if index >= len(str):
            return
        revers(index + 1, str)
        print(str[index])
    
    revers(0, 'abcde')
    • 反转列表: 不开辟新列表的情况下
    def revers(index=0, alist):
        if index >= len(alist):
            return alist
        ele = alist.pop()
        alist.insert(index, ele)
        revers(index+1, alist)
    • 给定一个链表, 交换每两个相邻节点  如  1, 2, 3, 4   ->  2, 1, 4, 3
    class Node():
        def __init__(self, item):
            self.item = item
            self.next = None
    
    class Link():
        def __init__(self):
            self.head = None
        def add(self, item):
            node = Node(item)
            if not self.head:
                self.head = node
                return
            cur = self.head
            while cur.next:
                cur = cur.next
            cur.next = node
            return
        def travel(self):
            if not self.head:
                print('空链表')
                return
            cur = self.head
            print(cur.item)
            while cur.next:
                cur = cur.next
                print(cur.item)
        def swap(self, node, n=1):
            if n:
                self.head = self.head.next
            if not node or not node.next:
                return
            node, node.next, node.next.next = node.next, node, node.next.next
            node.next.next = self.swap(node.next.next, 0)
            return node
    
        # 反转链表
        def reversList(self, head):
            pre = head
            cur = head.next
            pre.next = None
            while cur:
                tmp = cur.next
                cur.next = pre
                pre, cur = cur, tmp
            self.head = pre
            
        # 递归实现反转链表
        def revers(self, pre, cur, n=1):
            tmp = cur.next
            if n:
                pre.next = None
            cur.next = pre
            if tmp:
                self.revers(cur, tmp, 0)
            else:
                self.head = cur
            
  • 相关阅读:
    TP5.1 路由验证器验证返回json提示
    win10 docker ubuntu14.04 php 编译安装 php7.3.20
    ubuntu15.10 sources.list 修改
    秒杀系统设计
    class命名规范
    php实现阿里云签名类
    【小程序】应用的生命周期,页面的生命周期
    php.ini配置文件参数中文说明文档
    tp5.1 nginx配置
    phpstudycomposer thinkPHP5.1 使用
  • 原文地址:https://www.cnblogs.com/zhangjian0092/p/11743513.html
Copyright © 2011-2022 走看看