码迷,mamicode.com
首页 > 其他好文 > 详细

数据结构:广义表转置

时间:2018-11-29 01:23:11      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:range   sub   instance   返回   数据结构   coding   结构   list   def   

问题描述

设计算法,将指定的广义表的内容原地逆置。例如:若广义表GL为[1, [2, 3], 4, [5, [6, 7], 8], 9],逆置后GL为 [9, [8, [7, 6], 5], 4, [3, 2], 1] 。

基本思路

如题,一眼就能看出问题具有递归性,因此采用递归来求解,代码就非常简单了。

Python实现

#encoding = utf8

def reverse_table(table):
    ‘‘‘
    递归
    ‘‘‘
    if not isinstance(table,list) or len(table)==0: #元素不是list 或者 list的长度为0则返回
        return

    for sub_table in table:
        reverse_table(sub_table)
        
    table_len = len(table)
    for i in range(table_len//2):
        table[i], table[table_len-i-1] = table[table_len-i-1], table[i] #switch

    
if __name__ == "__main__":
    table=[1, [2, 3], 4, [5, [6, 7], 8], 9]
    reverse_table(table)
    print(table)

 

数据结构:广义表转置

标签:range   sub   instance   返回   数据结构   coding   结构   list   def   

原文地址:https://www.cnblogs.com/walter-xh/p/10035697.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!