2015-03-13 08:35:48      个评论    来源：累了就歇一会

## 图创建

### 邻接链表

``````struct Node{
int val;
int length;
Node* next;
Node(): val(0), length(0), next(NULL) {}
};

typedef Node* Graph;

Graph CreateG (Graph G){
int num;
scanf("%d", &num); // input the number of the vertex
G = (Graph)malloc(sizeof(struct Node) * (num+1)); //malloc memory for graph
G[0].length = num; //save the graph vertex number
degree = (int *)malloc((num+1) * sizeof(int));
memset(degree, 0, num*sizeof(int));
for (int i = 1; i <= num; i++) {
G[i].val = i;
G[i].next = NULL;
int outdegree = 0;
scanf("%d", &outdegree);
for (int j = 0; j < outdegree; j++) {
Node* temp = (Node*)malloc(sizeof(struct Node));
scanf("%d %d",&(temp->val), &(temp->length));
temp->next = G[i].next;
G[i].next = temp;
degree[temp->val] += 1;
}
}
return G;
}
``````

## 图打印

### 邻接链表

``````void PrintG (Graph G){
//    int length = sizeof(G)/sizeof(struct Node);
int length = G[0].length;
Node * temp;
for (int i = 1; i <= length; i++) {
temp = &G[i];
printf("Node: %d ",temp->val);
while (temp->next) {
printf("-> %d(%d)",temp->next->val, temp->next->length);
temp = temp->next;
}
printf("\n");
}
}``````