m0_61817339 2022-04-18 16:51 采纳率: 50%
浏览 36

使用python将二维数组转化为双链表结构

rt,已经用递归方法完成,现要求利用循环完成转化,感觉无从下手

img

img

  • 写回答

1条回答 默认 最新

  • 溪风沐雪 2022-04-18 23:39
    关注

    我研究了一下,写了个例子,实现了上下左右随意移动,就是不知道是否符合题意,你看看吧,

    class FourWayNode():
        def __init__(self,data,up=None,down=None,previous=None,next=None):
            self.data = data
            self.next = next
            self.previous = previous
            self.up = up
            self.down = down
    
    def constructDoublyLinkedListLoop(arr):
        nodeList = []
        for i in range(3) :
            v_node = [FourWayNode(j) for j in lst2d[i]]
            nodeList.append(v_node)
    
        for i in range(3) :
            for j in range(4):
                node = nodeList[i][j]
                if j==3:
                    node.next = nodeList[i][0]
                else:
                    node.next = nodeList[i][j+1]
                if j==0:
                    node.previous = nodeList[i][3]
                else:
                    node.previous = nodeList[i][j-1]
                if i==2:
                    node.down = nodeList[0][j]
                else:
                    node.down = nodeList[i+1][j]
                if i==0:
                    node.up = nodeList[2][j]
                else:
                    node.up = nodeList[i-1][j]
        head = nodeList[0][0]
        return head
    
    lst2d = [[5,4,7,10],
             [6,12,1,9],
             [8,2,3,11]]
    
    head = constructDoublyLinkedListLoop(lst2d)
    print("--------------------------------")
    print(head.data)
    head = head.next
    print(head.data)
    head = head.down
    print(head.data)
    head = head.next
    print(head.data)
    head = head.down
    print(head.data)
    head = head.next
    print(head.data)
    head = head.up
    print(head.data)
    head = head.up
    print(head.data)
    head = head.previous
    print(head.data)
    head = head.previous
    print(head.data)
    head = head.previous
    print(head.data)
    print("--------------------------------")
    
    
    评论

报告相同问题?

问题事件

  • 创建了问题 4月18日