我需要将哪些函数添加到此链接列表中?

发布于 2024-09-06 03:45:57 字数 3846 浏览 2 评论 0原文

我只是 C++ 的初学者。我想了解链表类中应该有哪些函数。

我认为应该有重载运算符<<和>>。如何改进代码(样式、错误等)?

编辑

这只是第一阶段,下一阶段将(希望)使用模板。

请查看整数列表的小代码(随附的 MyNODE.h 和 ListDriver1.cpp);

MyNODE.h

    // This is my first attempt to write linked list. Igal Spector, June 2010.

#include <iostream.h>
#include <assert.h>

//Forward Declaration of the classes:
class ListNode;
class TheLinkedlist;

// Definition of the node (WITH IMPLEMENTATION !!!, without test drive):


class ListNode{
 friend class TheLinkedlist;
public:
 // constructor:
 ListNode(const int& value, ListNode *next= 0);
 // note: no destructor, as this handled by TheLinkedList class.

 // accessor: return data in the node.
// int Show() const {return theData;}

private:
 int theData;  //the Data
 ListNode* theNext; //points to the next node in the list.
};

//Implementations:
//constructor:
inline ListNode::ListNode(const int &value,ListNode *next)
:theData(value),theNext(next){}


//end of ListNode class, now for the LL class:

class TheLinkedlist
{
public:
 //constructors:
 TheLinkedlist();
 virtual ~TheLinkedlist();
 // Accessors:
 void InsertAtFront(const &);
 void AppendAtBack(const &);

// void InOrderInsert(const &);
 bool IsEmpty()const;//predicate function
 void Print() const;
private:
 ListNode * Head; //pointer to first node
 ListNode * Tail; //pointer to last node.
};

//Implementation:

//Default constructor
inline TheLinkedlist::TheLinkedlist():Head(0),Tail(0) {}

//Destructor
inline TheLinkedlist::~TheLinkedlist(){
 if(!IsEmpty()){  //list is not empty
 cout<<"\n\tDestroying Nodes"<<endl;
 ListNode *currentPointer=Head, *tempPtr;

  while(currentPointer != 0){ //Delete remaining Nodes.
   tempPtr=currentPointer;
  cout<<"The node: "<<tempPtr->theData <<" is Destroyed."<<endl<<endl;
  currentPointer=currentPointer->theNext;
  delete tempPtr;
  }
 Head=Tail = 0;  //don't forget this, as it may be checked one day.
 }
}

//Insert the Node to the beginning of the list:
void TheLinkedlist::InsertAtFront(const int& value){
 ListNode *newPtr = new ListNode(value,Head);
 assert(newPtr!=0);

 if(IsEmpty())  //list is empty
  Head = Tail = newPtr;
 else {    //list is NOT empty
  newPtr->theNext = Head;
  Head = newPtr;
 }
}

//Insert the Node to the beginning of the list:
void TheLinkedlist::AppendAtBack(const int& value){
 ListNode *newPtr = new ListNode(value, NULL);
 assert(newPtr!=0);

 if(IsEmpty())  //list is empty
  Head = Tail = newPtr;
 else {    //list is NOT empty
  Tail->theNext = newPtr;
  Tail = newPtr;
 }
}

//is the list empty?
inline bool TheLinkedlist::IsEmpty() const
  { return (Head == 0); }

// Display the contents of the list
void TheLinkedlist::Print()const{
 if ( IsEmpty() ){
  cout << "\n\t The list is empty!!"<<endl;
  return;
 }

 ListNode *tempPTR = Head;
 cout<<"\n\t The List is: ";

 while ( tempPTR != 0 ){
  cout<< tempPTR->theData <<"  ";
  tempPTR = tempPTR->theNext;
 }
 cout<<endl<<endl;
}
//////////////////////////////////////

测试驱动程序:

//Driver test for integer Linked List.

#include <iostream.h>
#include "MyNODE.h"

// main Driver
int main(){

 cout<< "\n\t This is the test for integer LinkedList."<<endl;

 const int arraySize=11,
   ARRAY[arraySize]={44,77,88,99,11,2,22,204,50,58,12};

 cout << "\n\tThe array is: "; //print the numbers.
 for (int i=0;i<arraySize; i++)
  cout<<ARRAY[i]<<",  ";

 TheLinkedlist list;   //declare the list

 for(int index=0;index<arraySize;index++)
  list.AppendAtBack( ARRAY[index] );//create the list

 cout<<endl<<endl;
 list.Print();    //print the list

 return 0;     //end of the program.
}

I'm just beginner to C++. I would like to understand what functions should be in the Linked list class.

I think there should be overloaded operators << and >>. How can I improve the code (style, errors, etc)?

Edit

This is only first stage, the next one will be (hopefully) with templates.

Please review the small code for the integer List (enclosed MyNODE.h and ListDriver1.cpp);

MyNODE.h

    // This is my first attempt to write linked list. Igal Spector, June 2010.

#include <iostream.h>
#include <assert.h>

//Forward Declaration of the classes:
class ListNode;
class TheLinkedlist;

// Definition of the node (WITH IMPLEMENTATION !!!, without test drive):


class ListNode{
 friend class TheLinkedlist;
public:
 // constructor:
 ListNode(const int& value, ListNode *next= 0);
 // note: no destructor, as this handled by TheLinkedList class.

 // accessor: return data in the node.
// int Show() const {return theData;}

private:
 int theData;  //the Data
 ListNode* theNext; //points to the next node in the list.
};

//Implementations:
//constructor:
inline ListNode::ListNode(const int &value,ListNode *next)
:theData(value),theNext(next){}


//end of ListNode class, now for the LL class:

class TheLinkedlist
{
public:
 //constructors:
 TheLinkedlist();
 virtual ~TheLinkedlist();
 // Accessors:
 void InsertAtFront(const &);
 void AppendAtBack(const &);

// void InOrderInsert(const &);
 bool IsEmpty()const;//predicate function
 void Print() const;
private:
 ListNode * Head; //pointer to first node
 ListNode * Tail; //pointer to last node.
};

//Implementation:

//Default constructor
inline TheLinkedlist::TheLinkedlist():Head(0),Tail(0) {}

//Destructor
inline TheLinkedlist::~TheLinkedlist(){
 if(!IsEmpty()){  //list is not empty
 cout<<"\n\tDestroying Nodes"<<endl;
 ListNode *currentPointer=Head, *tempPtr;

  while(currentPointer != 0){ //Delete remaining Nodes.
   tempPtr=currentPointer;
  cout<<"The node: "<<tempPtr->theData <<" is Destroyed."<<endl<<endl;
  currentPointer=currentPointer->theNext;
  delete tempPtr;
  }
 Head=Tail = 0;  //don't forget this, as it may be checked one day.
 }
}

//Insert the Node to the beginning of the list:
void TheLinkedlist::InsertAtFront(const int& value){
 ListNode *newPtr = new ListNode(value,Head);
 assert(newPtr!=0);

 if(IsEmpty())  //list is empty
  Head = Tail = newPtr;
 else {    //list is NOT empty
  newPtr->theNext = Head;
  Head = newPtr;
 }
}

//Insert the Node to the beginning of the list:
void TheLinkedlist::AppendAtBack(const int& value){
 ListNode *newPtr = new ListNode(value, NULL);
 assert(newPtr!=0);

 if(IsEmpty())  //list is empty
  Head = Tail = newPtr;
 else {    //list is NOT empty
  Tail->theNext = newPtr;
  Tail = newPtr;
 }
}

//is the list empty?
inline bool TheLinkedlist::IsEmpty() const
  { return (Head == 0); }

// Display the contents of the list
void TheLinkedlist::Print()const{
 if ( IsEmpty() ){
  cout << "\n\t The list is empty!!"<<endl;
  return;
 }

 ListNode *tempPTR = Head;
 cout<<"\n\t The List is: ";

 while ( tempPTR != 0 ){
  cout<< tempPTR->theData <<"  ";
  tempPTR = tempPTR->theNext;
 }
 cout<<endl<<endl;
}
//////////////////////////////////////

The test Driver:

//Driver test for integer Linked List.

#include <iostream.h>
#include "MyNODE.h"

// main Driver
int main(){

 cout<< "\n\t This is the test for integer LinkedList."<<endl;

 const int arraySize=11,
   ARRAY[arraySize]={44,77,88,99,11,2,22,204,50,58,12};

 cout << "\n\tThe array is: "; //print the numbers.
 for (int i=0;i<arraySize; i++)
  cout<<ARRAY[i]<<",  ";

 TheLinkedlist list;   //declare the list

 for(int index=0;index<arraySize;index++)
  list.AppendAtBack( ARRAY[index] );//create the list

 cout<<endl<<endl;
 list.Print();    //print the list

 return 0;     //end of the program.
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅沫记忆 2024-09-13 03:45:57

链接列表类中应包含哪些函数?

这取决于您需要用它做什么。至少,人们应该能够向其中添加元素,并查看列表中的元素。

(这是常识。因为如果您无法以任何方式修改或读取您的列表,它还能用来做什么?)


我认为应该有重载运算符<<和>>;

为什么?他们会做什么?我想您的意思是 operator << 进行插入,类似于将对象插入到 C++ IO 流中;但 operator >> 到底应该做什么?提取/删除某种元素?如果您以这种方式实现插入和提取(?),可能没有人能够理解您的链表类。链表不是 IO 流。 (为了简洁起见,选择了具有 IO 流的运算符。)

如果操作的含义不清楚,我建议您不要重载运算符。我建议您更明确地命名您的操作,例如通过提供方法 addremove (我仍在猜测后一个操作的含义>> ; 顺便说一句。)


如何改进代码(样式、错误等)?

我不想将此作为我答案的要点,所以只是非常简短地从顶部开始我的想法是,有一些问题:

  • 您应该#include而不是#include,然后添加一个使用命名空间 std; 或编写(例如)std::cout 而不是 cout

  • 尝试摆脱朋友。您应该能够以不需要这样做的方式设计您的类。 friend 很容易被滥用来绕过正确的封装。但封装是 OOP 中您绝对应该考虑的事情。

  • 虽然这不是给 C++ 初学者的建议,但如果您将链表类制作为模板类,它可以存储与 int 不同的值。将此作为未来改进的提示。


最后:

  • 只需使用 C++ 标准库中包含的 STL(“标准模板库”)容器即可。我知道“自己动手”有助于理解这些数据结构的工作原理,但请注意,C++ 标准库已经包含一组可靠且高效的数据容器。

What functions should be in the Linked list class ?

That depends on what you need to do with it. At the very least, one should probably be able to add elements to it, and to look at the elements in the list.

(This is common sense. Because if you can't modify or read your list in any way, what could it ever be used for?)


I think there should be overloaded operators << and >>;

Why? What would they do? I suppose you mean operator << to do insertion, similar to how objects are inserted into C++ IO streams; but what exactly should operator >> do? Extraction/removal of elements of some sort? If you implement insertion and extraction (?) in this manner, probably no-one will be able to understand your linked list class. A linked list is not an IO stream. (Those operators with IO streams were chosen for brevity.)

I would advise you against operator overloading if the meaning of the operation is not clear. I would suggest you name your operations more explicitly, e.g. by providing methods add and remove (I'm still guessing at the meaning of the latter operation >> btw.).


How can I improve the code (style, errors, etc)?

I don't want to make this the main point on my answer, so just very briefly off the top of my head, some issues:

  • You should #include <iostream> instead of #include <iostream.h>, and then either add a using namespace std; or write (e.g.) std::cout instead of cout.

  • Try to get rid of the friend. You should be able to design your classes in a way that doesn't require this. friend is easily misused to get around proper encapsulation. But encapsulation is something you should definitely think about in OOP.

  • Though that's not an advice to give to a C++ beginner, if you made your linked list class into a template class, it could store different values than just ints. Just take this as a hint for future improvements.


And finally:

  • Just use the STL ("Standard Template Library") containers which are included in the C++ standard library. I know that "rolling your own" helps understanding how these data structures work, but be aware that the C++ standard library already includes a solid and efficient set of data containers.
百合的盛世恋 2024-09-13 03:45:57
  1. 0 应该为 NULL

  2. 仅在您不关心代码是否公开的情况下内联,通常实现会放入单独的文件 Mylist.cpp 文件中。

  3. 为什么你的析构函数是虚拟的,你有继承吗?

  4. 您可以只定义结构节点而不是单独的类,最好定义您的列表以进行练习,就像在 stl 中一样。 http://www.sgi.com/tech/stl/List.html http://www.cplusplus.com/reference/stl/list/

在 C++ 中常用向量与 Java 中的链表
http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html< /a>

  1. 0 should be NULL

  2. inline only in the case that you don't care that your code will be public, usually implementation puts in separate file Mylist.cpp file.

  3. Why your destructor virtual, do you have inheritance ?

  4. You can just define struct node instead separate class its better define your list for practice like in stl. http://www.sgi.com/tech/stl/List.html http://www.cplusplus.com/reference/stl/list/

In C++ common to use vector vs linked list in Java
http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文