//创建邻接链表
//表节点
struct arcLNode
{
int adjvex = -1; //存储点节点下表
int lineId = -1; //边的id
std::shared_ptr<arcLNode> nextarc =nullptr;
};
//表头节点
struct headLNode
{
headLNode(iCoord3d pt) : point(pt) {};
~headLNode() {};
iCoord3d point; //节点坐标
std::shared_ptr<arcLNode> firstarc=nullptr; //表头连接的第一个节点
bool visited = false; //是否访问过
};
//邻接链表
struct AdjacentListGraph
{
int vertexNum = 0, edgeNum = 0;
vector<headLNode> node;
};
int main()
{
//创建邻接链表
AdjacentListGraph graph;
graph.edgeNum = static_cast<int>(lines.size());
graph.vertexNum = static_cast<int>(points.size());
//存储点
for_each(points.begin(), points.end(), [&](const iCoord3d points) {
headLNode hNode(points);
graph.node.emplace_back(hNode);
});
//存储起始点在邻接表的位置
int originNum(0);
//存储边的信息
for (const SegmentLine&line:lines)
{
//获取边的两个端点
vector<iCoord3d> icPt {line.startPt, line.endPt, startPt};
vector<int> nums;
for (const iCoord3d&pt:icPt)
{
for (int i = 0; i < graph.vertexNum; ++i)
{
//如果两个点的距离大于1就不是同一个点
if (pt.DistPtPt(graph.node[i].point) > 1)
continue;
nums.emplace_back(i);
break;
}
}
iCoord3d sPt(line.startPt), ePt(line.endPt);
//获取两个点的位置
int sNum(nums[0]), eNum(nums[1]);
originNum = nums[2];
//如果第一点为空
if (!graph.node[sNum].firstarc)
{
std::shared_ptr<arcLNode> arcNode(new arcLNode());
arcNode->adjvex = eNum;
arcNode->lineId = line.id;
graph.node[sNum].firstarc = std::move(arcNode);
}
else
{
std::shared_ptr<arcLNode> tempNode = graph.node[sNum].firstarc;
//找到最后一个节点
while (tempNode->nextarc)
tempNode = tempNode->nextarc;
std::shared_ptr<arcLNode> arcNode(new arcLNode());
arcNode->adjvex = eNum;
arcNode->lineId = line.id;
tempNode->nextarc = std::move(arcNode);
}
if (!graph.node[eNum].firstarc)
{
std::shared_ptr<arcLNode> arcNode(new arcLNode());
arcNode->adjvex = sNum;
arcNode->lineId = line.id;
graph.node[eNum].firstarc = std::move(arcNode);
}
else
{
std::shared_ptr<arcLNode> tempNode = graph.node[eNum].firstarc;
//找到最后一个节点
while (tempNode->nextarc)
tempNode = tempNode->nextarc;
std::shared_ptr<arcLNode> arcNode(new arcLNode());
arcNode->adjvex = sNum;
arcNode->lineId = line.id;
tempNode->nextarc = std::move(arcNode);
}
}
}
邻接链表代码实现
于 2021-09-06 15:38:00 首次发布