实现queue和stack的拷贝构造函数的一个思路

来源:互联网 发布:监管网络的部门 编辑:程序博客网 时间:2024/05/27 09:45

首先声明一下这并非本人的成果,而是郑斯达师兄开设的stack题目的标准答案。queue的拷贝方法则是我基于这个修改得到的。

首先从stack(栈)开始

Stack(const Stack<ElementType> &stack) {            if (this == &stack) return;            top_node = NULL;            node_num = 0;            if (stack.top_node == NULL) return;             Node *copy_temp = stack.top_node;            Node *top_temp = NULL;            while (copy_temp) {                if (top_temp == NULL) {                    top_node = new Node(copy_temp->element);                    top_temp = top_node;                } else {                    top_node->next = new Node(copy_temp->element);                    top_node = top_node->next;                }                copy_temp = copy_temp->next;            }            top_node = top_temp;            node_num = stack.node_num;        }     

首先 若两个栈的地址一样,则直接返回,不做任何操作;之后先对当前栈初始化,如果需要拷贝的栈也为初始化状态(栈顶指针为NULL)则直接返回,这样得到的栈同样是初始化的栈。
之后,声明两个指针,分别赋值拷贝栈的栈顶指针和NULL。 此处Node为结构体,代码如下

     struct Node {            ElementType element;            Node* next;            Node(ElementType ele, Node *n = NULL) {                element = ele;                next = n;            }        };

top_temp的作用是让第一次循环的时候只构造栈顶,同时储存栈顶的指针,方便第二次以及之后的循环。
第二次开始执行else内代码,即拷贝栈顶的下一个数据,然后让top_node变为刚刚拷贝好的数据,以达到循环拷贝余下所有数据直到栈底的目的。
循环结束后再将top_node的地址更正为真正的栈顶地址,从而实现栈的拷贝

queue与stack相似,只是初始化需要的指针多了一个队尾指针back_node,其他的只要把stack的top_node改为queue的队首指针front_node即可

Queue(const Queue & another) {        if (this == &another) return;        front_node = NULL;        back_node = NULL;        node_num = 0;        if (another.front_node == NULL)return;        Node *copy = another.front_node;        Node* temp = NULL;        while(copy) {            if (temp == NULL) {                front_node = new Node(copy->element);                temp = front_node;        } else {            front_node->next = new Node(copy->element);            front_node = front_node->next;        }            copy = copy->next;      }        front_node = temp;        node_num = another.node_num;    }
原创粉丝点击