邻接表--图 部分代码

h文件

#pragma once

#include <iostream>
using namespace std;
typedef int E;
typedef char T;
const int defaultVertices = 30;
struct Edge {
int dest;
E cost;
Edge *link;
Edge() {}
};
struct Vertex {
T data;
Edge *adj;
};
class Graphlnk {
private:
Vertex * NodeTable;
int numVertices;
int maxVertices;
int getVertexPos(const T vertx) {
for (int i = 0; i < numVertices; i++) {
if (NodeTable[i].data == vertx)
return i;
}
return -1;
}
public:
Graphlnk(int sz = defaultVertices);
~Graphlnk();
T getValue(int i) {
return (i >= 0 && i < numVertices) ? NodeTable[i].data : 0;
}
E getWeight(int v1, int v2);
bool insertVertex(const T& vertex);
bool removeVertex(int v);
bool insertEdge(int v1, int v2, E cost);
bool removeEdge(int v1, int v2);
int getFirstNeighbor(int v);
int getNextNeighbor(int v, int w);

};

cpp文件

#include "stdafx.h"
#include "graph_2.h"
#include <iostream>
using namespace std;
Graphlnk::Graphlnk(int sz)
{
maxVertices = sz;
numVertices = 0;
NodeTable = new Vertex[maxVertices];
if (NodeTable == NULL) {
cerr << "graphlnk error" << endl;
exit(1);
}
for (int i = 0; i < maxVertices; i++) {
NodeTable[i].adj = NULL;
}
}


Graphlnk::~Graphlnk()
{
for (int i = 0; i < numVertices; i++) {
Edge *p = NodeTable[i].adj;
while (p != NULL) {
NodeTable[i].adj = p->link;
delete p;
p = NodeTable[i].adj;
}
}
delete[] NodeTable;
}


int Graphlnk::getFirstNeighbor(int v)
{
if (v != -1) {
Edge *p = NodeTable[v].adj;
if (p != NULL) {
return p->dest;
}
}
return -1;
}


int Graphlnk::getNextNeighbor(int v, int w)
{
if (v != -1) {
Edge *p = NodeTable[v].adj;
while (p != NULL && p -> dest != w) {
p = p->link;
}
if (p != NULL && p->link != NULL)
return p->link->dest;
}
return -1;
}

原文地址:https://www.cnblogs.com/wangjianupc/p/10587219.html