簡體   English   中英

LinkedList C ++實現

[英]LinkedList C++ implementation

我剛剛創建了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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM