简体   繁体   English

复制链表堆栈类的构造方法:我的是向后复制

[英]Copy Constructor for a Linked List Stack Class: mine is copying backwards

So I've combed through what is already on this site about linked list stacks. 因此,我梳理了该站点上有关链表堆栈的内容。 Mine is a template class and I've also created a Node structure. 我的是一个模板类,我还创建了一个Node结构。 From what I've seen with other questions, I understand that this isn't always the best considering standard library implementations already existing in C++ as mentioned in this first answer BUT this is for an assignment so it's all in the name of science. 从我对其他问题的理解中,我了解到,考虑到第一个答案中提到的 C ++中已经存在的标准库实现,这并不总是最好的方法,但这只是为了分配作业,所以这一切都是以科学的名义进行的。

This is the structure so you have an idea of what I've named things 这是结构,因此您对我已命名的事物有一个了解

template <class T>
struct Node
{ public:
  //data members
  T data;
  Node<T> *next;

  //methods
  Node(const T &);
};


template <class T>
Node<T>::Node(const T &newData)
{
data = newData;
next = NULL;
}

Nothing fancy. 没有什么花哨。 These are my Stack class's data members for reference 这些是我Stack类的数据成员以供参考

private:
  Node<T> *stkTop;  //or headPtr, so to speak
  int stkSize;

And this is my copy constructor as is 这是我的复制构造函数

template <class T>
Stack<T>::Stack(const Stack<T> &existStack)
{

Node<T> *currentNode = existStack.stkTop;
stkSize = 0;
stkTop = NULL;

while( currentNode != NULL )
{
Node<T> *ptr = new Node<T>(0);

ptr -> data = (currentNode -> data);
ptr -> next = stkTop;
stkTop = ptr;

currentNode = currentNode -> next;

stkSize++;
}

So far so good... I'm even obeying the Rule of Three. 到目前为止一切顺利……我什至遵守三定律。 I also have an overloaded assignment operator and a destructor (though to be honest the assignment operator is the same exact code, I've just included a test for self assignment). 我也有一个重载的赋值运算符和一个析构函数(尽管说实话,赋值运算符是相同的精确代码,但我只是包含了一个自赋值测试)。

I mean, it KIND OF works. 我的意思是,它确实有效。 All the values show up...just in reverse order... Totally stumped. 所有值都显示出来……只是相反的顺序……完全被卡住了。

The implementing program I have just runs a couple short tests like explicitly calling the constructor, assigning a stack to another stack, assigning a stack to itself. 我刚刚执行的实现程序运行了一些简短的测试,例如显式调用构造函数,将堆栈分配给另一个堆栈,将堆栈分配给它自己。 Everything looks fine except for the order. 除了顺序外,其他一切看起来都很好。 I'm assuming I'm traversing my list wrong or something when copying values over....I don't know :( 我假设我在复制值时遍历列表错误或其他问题....我不知道:(

You are going down (stack top to stack bottom) existStack with currentNode while you are going up this stack. 在上堆栈时,您将使用currentNode向下(堆栈顶部至堆栈底部)存在。 The first item you inserted should have been the top, but instead the last node you inserted is the top. 您插入的第一个项目应该是顶部,但是插入的最后一个节点应该是顶部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM