#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int datatype;
typedef struct _linknode_ {
datatype vertex;
struct _linknode_ *next;
}linknode;
linknode *creat_linknode(datatype value)
{
linknode *p = (linknode *)malloc(sizeof(linknode));
memset(p,0,sizeof(linknode));
p->vertex = value;
}
void insert_linknode(linknode *head,datatype v)
{
linknode *p = NULL,
*new = NULL;
if (NULL == head)
return ;
p = head;
while(NULL != p->next && p->next->vertex <= v)
p = p->next;
if(p->vertex == v)
return ;
new = creat_linknode(v);
new->next = p->next;
p->next = new;
return ;
}
void annul_linklist(linknode *head)
{
linknode *p = NULL;
while(head != NULL)
{
p = head;
head = head->next;
free(p);
}
}
int main()
{
datatype nu;
datatype v1 = -1,v2 = -1;
linknode *p = NULL;
puts("input the number of vertex:");
while( 1 != scanf("%d",&nu))//输入一个图共有几个顶点
getchar();
const int N = nu;
printf("the number of vertex is : %d\n",N);
linknode *vertexs = (linknode *)malloc(sizeof(linknode) * N);
memset(vertexs,0,sizeof(linknode) * N);
puts("input the relation of yout graph,like [1,2]:");//边的输入
while (1)
{
while( 2 != scanf("%d,%d",&v1,&v2))
getchar();
if(v1 == v2)
break;
if(v1 < 0 || v1 >= N || v2 < 0 || v2 >= N)
continue;
insert_linknode(vertexs + v1,v2);
insert_linknode(vertexs + v2,v1);
}
for(v1 = 0; v1 < N; v1 ++)
{
p = vertexs[v1].next;
printf("V%d: ",v1);
while(NULL != p)
{
printf(" V%d,",p->vertex);
p = p->next;
}
putchar(8);
putchar(32);
putchar(10);//这三个是为了消去打印时最后留下的那个逗号
annul_linklist(vertexs[v1].next);//最后进的清空
}
free(vertexs);
return 0;
}
转载于:https://my.oschina.net/u/130360/blog/68220