Python实现回溯指针

Python实现回溯指针

Python没有指针的概念,因此不能像C++那样通过指向父结点的指针访问父结点的方法。
比如在树中,要实现指向父结点的指针,C++ 的代码为:

#include<iostream>
using namespace std;

class Node;  // 前置声明
class Node{
public:
    Node():_n(0),_parent(NULL),_child(NULL){}
    void expand(Node& child){  // 开辟孩子结点,孩子结点与父结点指针相互指向
        _child=&child;
        _child->_parent=this;
    }

    Node* _child;
    Node* _parent;
    int _n;
};

int main(){
    Node r1;
    Node r2;
    r2._n=1;
    r1.expand(r2);  // r2作为r1的孩子
    cout<<r1._n<<endl;
    cout<<r2._n<<endl;
    cout<<r2._parent->_n<<endl;
    return 0;
}
/* 输出: 0 1 0 */

虽然Python中没有指针的概念,但是Python是传引用的,因此可以引用父结点。

class Node(object):

    def __init__(self,parent=None):
        self._parent=parent
        self._child=Node
        self._n=0

    def expand(self,node):  # 增加孩子结点
        self._child=node  # 靠引用完成指针的链接
        node._parent=self 
        self._child._n=self._n+1


n1=Node(None)
n2=Node(None)
n1.expand(n2)  # n2作为n1的孩子

# 两个都是True
print(n1._child is n2)
print(n1 is n2._parent)

print(n1._n)
print(n2._n)

由此可知,Python不是可以递归嵌套使用类的,它实际上是靠引用来完成指针的操作。

    原文作者:骑士周游问题
    原文地址: https://blog.csdn.net/qq_35976351/article/details/79666048
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞