链接列表C++实现



我刚刚创建了一个LinkedList的实现(仅用于自我教育目的)。我让它运行,但输出结果有点奇怪......这是代码:

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
using namespace std;
template <class T>
class Node{
T datum;
Node<T> *_next;
public:
 Node(T datum)
{
    this->datum = datum;
    _next = NULL;
}
 void setNext(Node* next)
 {
     _next = next;
 }
 Node* getNext()
 {
     return _next;
 }
 T getDatum()
 {
     return datum;
 }          
};
template <class T>
class LinkedList{
Node<T> *node;
Node<T> *currPtr;
Node<T> *next_pointer;
int size;
public:
LinkedList(T datum)
  {
      node = new Node<T>(datum);
      currPtr = node;  //assignment between two pointers.
      next_pointer = node;
      size = 1;
  }
LinkedList* add(T datum)  // return pointer type.
{
   Node<T> *temp = new Node<T>(datum);
   currPtr->setNext(temp);
   currPtr = temp;
   size++;
   cout<<datum<<" is added.";
   return this; //pointer type specification
}
T next()
{
   T data = (*next_pointer).getDatum();
   cout<<data<<" is visited.";
   next_pointer = next_pointer->getNext();
   return data;
}
int getSize()
{
   return size;
}   
};

现在我尝试使用LinkedList:

int main()
{
LinkedList<int> *list = new LinkedList<int>(1);
list->add(2)->add(3)->add(4);
cout<<endl;
printf("%d %d %d %d",list->next(),list->next(),list->next(),list->next());  \One
cout<<list->next()<<"n"<<list->next()<<"n"<<list->next()<<"n"<<list->next()<<endl; \Two
cout<<list->next()<<endl;\Three
cout<<list->next()<<endl;
cout<<list->next()<<endl;
cout<<list->next()<<endl;
}

输出 One 将显示数据:4 3 2 1。两个将显示 4 3 2 1。三个将显示 1 2 3 4。我不知道在运行时发生了什么。他们都应该以 1 2 3 4 序列输出数据......感谢您的帮助!谢谢!

未指定参数的计算顺序,因此:

printf("%d %d %d %d",list->next(),list->next(),list->next(),list->next());

可以先评估最后一个list->next(),或者中间一个......

编辑:只是解决我认为是问题的问题,因为我怀疑这是实际的代码:http://ideone.com/avEv7

相关内容

  • 没有找到相关文章

最新更新