Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- using namespace std;
- struct node {
- int i = NULL;
- vector <int> edges;
- node* nextVertex;
- node(int n) {
- i = n;
- nextVertex = NULL;
- }
- };
- typedef node Node;
- class Graph {
- Node* head;
- int N;
- public:
- Graph(int t){
- this->N = t;
- }
- void addEdge(int, int, bool);
- void addVertex(int);
- node* existVertex(int);
- void print();
- };
- node* Graph::existVertex(int i) {
- node* cur = this->head;
- while (cur != NULL) {
- if (cur->i == i) {
- return cur;
- break;
- }
- cur = cur->nextVertex;
- }
- return 0;
- }
- void Graph::addEdge(int i, int j, bool status) {
- if (this->head == NULL) {
- this->head = new node(i);
- this->head->edges.push_back(j);
- node* cur = this->head;
- if (status == true) {
- cur->nextVertex = new node(j);
- cur->nextVertex->edges.push_back(i);
- }
- }
- else if (existVertex(i) != NULL) {
- node* cur = existVertex(i);
- cur->edges.push_back(j);
- if (existVertex(j) == NULL)
- cur->nextVertex = new node(j);
- if (status == true) {
- cur->nextVertex->edges.push_back(i);
- }
- }
- else {
- node* cur = this->head;
- while (cur->nextVertex != NULL) cur = cur->nextVertex;
- cur->nextVertex = new node(i); cur->edges.push_back(j);
- if (existVertex(j) == NULL)
- cur->nextVertex = new node(j);
- if (status == true) {
- cur->nextVertex->edges.push_back(i);
- }
- }
- }
- void Graph::addVertex(int i) {
- if (existVertex(i) == NULL) {
- node* cur = this->head;
- while (cur->nextVertex != NULL) cur = cur->nextVertex;
- cur->nextVertex = new node(i);
- }
- }
- void Graph::print() {
- node* cur = this->head;
- while (cur != NULL) {
- cout << cur->i << " -> ";
- if (cur->edges.size() == 1) {
- cout << *cur->edges.begin();
- }
- else {
- auto it = cur->edges.begin();
- auto end = cur->edges.end();
- while (it != end) {
- cout << *it << " ";
- it++;
- }
- }
- cur = cur->nextVertex;
- printf("\n");
- }
- }
- int main() {
- Graph G(10);
- G.addEdge(1, 7, true);
- G.addEdge(7, 5, true);
- G.addVertex(4);
- G.print();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement