LinkedList C ++实现 [英] LinkedList C++ implementation

查看:56
本文介绍了LinkedList C ++实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I just created an implementation of LinkedList(just for self-education purpose.). I made it run, but the output result is kind of weird... Here is the code:

#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:

Now I tried to use 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 21.三个将显示1 2 3 4.我不知道在运行时发生了什么.所有这些都应该以1 2 3 4的顺序输出数据...非常感谢您的帮助!谢谢!

The output One will display the data : 4 3 2 1. Two will display 4 3 2 1. Three will display 1 2 3 4. I don't know what happened during the runtime. All of them should output the data in 1 2 3 4 sequence... I'd appreciate your help! Thanks!

推荐答案

未指定参数的评估顺序,因此:

The order in which parameters are evaluated is unspecified, so:

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

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

could evaluate the last list->next() first, or the middle one...

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

Just tackling what I assume is the issue, as I doubt that's the actual code: http://ideone.com/avEv7

这篇关于LinkedList C ++实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆