将数据存储到链表中

Storing Data into a Linked List C++

本文关键字:链表 存储 数据      更新时间:2023-10-16

输入格式如下:

    5
    1 2  9.0
    1 3 12.0
    2 4 18.0
    2 3  6.0
    2 5 20.0
    3 5 15.0
    0
    1 5

第一个数字是图中顶点的个数。接下来到0的线是图的边。第一个和第二个数字是顶点,第三个数字是它们之间的边的距离。我不知道如何将数据存储到列表邻接的每个顶点时读取它。例如,顶点1将有两个列表单元格,包含2 9.0和3 12.0。我还需要把1,9和1,12放入顶点2和3。但是我不知道如何将数据存储到ListCells

Code so Far:

#include <cstdio>
using namespace std;
typedef ListCell* List;
struct ListCell
{
   ListCell* next;
   int vertex;
   double weight;
   ListCell(int v, double w, ListCell* nxt)
   {
      vertex = v;
      weight = w;
      next = nxt;
   }
};
struct Vertex
{
   bool signaled;
   long distance;
   Vertex next;
   List adjacency;    
};
struct Graph
{
   int     numVertices;
   Vertex* vertexInfo;
   Graph(int n)
   {
      numVertices = n;
      vertexInfo  = new Vertex[n+1];
      for(int i = 1; i <= n; i++)
      {
         vertexInfo[i].signaled = false;
      }
   }
};
//==============================================================
//                   readIn
//==============================================================
// 
//==============================================================
void readIn()
{
   int n, p1, p2;
   double edge;
   scanf("%i ", &n);
   Graph(n);
   while(scanf("%i " &p1) != 0)
   {
   }
}

我用一种适合业务逻辑的方式来定义数据结构。

我建议你看一看《计算机编程艺术》,了解一些最佳实践。

关注"Linear Lists"章节

提示:遍历列表并附加新节点(请注意角落情况):

Vertex* v = vertexInfo[i];
while (v->next!=null) {
   v = v->next;
}
v->next = new Vertex(....);