使用节点和链表

Using nodes and Linked List

本文关键字:链表 节点      更新时间:2023-10-16

我正试图创建一个"链表",但遇到了麻烦,我对如何实现"节点"有点困惑。

相互指向的节点集合被视为链表,对吗?我正在尝试创建一个函数,该函数接受一个数组及其大小,我应该接受每个元素,并能够在将其放入列表时对其进行排序,然后将其按顺序放回数组中。我该怎么做?我知道一个节点包含某个元素,以及指向下一个节点的指针。STL中是否已经有一个结构,或者我必须从头开始制作它?

有人能帮我开始吗?(除了或补充我已有的)。我也不知道如何从数组的元素到节点的元素,以及如何按顺序排序。我现在正在使用int,我希望转到模板。非常感谢您的帮助!

EDIT)顺便说一下,这是一个头文件。。。

using namespace std;
/***********************************************
 * NODE
 ***********************************************/
struct Node
{
   int data;
   Node * pNext;
};
/***********************************************
 * INSERTION SORT
 * Sort the items in the array
 **********************************************/
//template <class T>
void sortInsertion(int array[], int num)
{
   // Make sure we can list the elements unsorted
   cout << "Testing sortInsertion()...nn";
   cout << "Unsorted:n";
   for (int i = 0; i < num; i++)
      cout << "num "<< i + 1 << ": " << array[i] << endl;
   cout << endl;
   cout << "Sorted:n";
   // Okay, make the head of the list...
   Node *pHead;
   // Loop through each element and insert it into the list, depending on order
   for (int i = 0; i < num; i++);
   // Loop through each node, and transfer each element into the array.
   for(const Node *p = pHead; p; p = p -> pNext)
   {
      int i = 0;
      array[i] = p -> data;
      i++;
   }
}

此行

 for (int i = 0; i < num; i++);

相当于

i = num;

这个

for(const Node*p=pHead;p;p=p->pNext){int i=0;array[i]=p->数据;i++;}

我认为有一个编译错误,但如果真的发生了,那只是设置array 中的第一个项目

但是为什么不使用STL呢?