逆序输入
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <malloc.h> 4 #define maxn 1000 5 6 //邻接表(点很多,边较少) 7 //共有n个点,点编号为1~n,m条边 8 //无向图 9 10 struct node 11 { 12 long value; 13 struct node *next; 14 }*d[maxn+1]; 15 16 int main() 17 { 18 struct node *p; 19 long n,m,i,x,y; 20 scanf("%ld%ld",&n,&m); 21 for (i=1;i<=n;i++) 22 d[i]=NULL; 23 //点在链表的顺序与输入的顺序相反 24 for (i=1;i<=m;i++) 25 { 26 scanf("%ld%ld",&x,&y); 27 //to point x 28 ///新创一个内存空间,p指针指向这个内存空间(结构体) 29 p=(struct node *) malloc (sizeof(struct node)); 30 p->value=y; 31 ///p指向的结构体的内部结构体指针next指向d[x](之前的数据) 32 p->next=d[x]; 33 ///当前数据在起始指针位置 34 d[x]=p; 35 //to point y 36 //Don‘t forget initialization 37 p=(struct node *) malloc (sizeof(struct node)); 38 p->value=x; 39 p->next=d[y]; 40 d[y]=p; 41 } 42 for (i=1;i<=n;i++) 43 { 44 printf("Point %ld:",i); 45 p=d[i]; 46 while (p) 47 { 48 printf(" %ld",p->value); 49 p=p->next; 50 } 51 printf("\n"); 52 } 53 return 0; 54 } 55 /* 56 Input: 57 6 9 58 1 2 59 1 3 60 1 4 61 2 5 62 3 4 63 3 5 64 3 6 65 4 6 66 5 6 67 Output: 68 Point 1: 4 3 2 69 Point 2: 5 1 70 Point 3: 6 5 4 1 71 Point 4: 6 3 1 72 Point 5: 6 3 2 73 Point 6: 5 4 3 74 */
正序输入:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <malloc.h> 4 #define maxn 1000 5 6 //邻接表(点很多,边较少) 7 //共有n个点,点编号为1~n,m条边 8 //无向图 9 10 struct node 11 { 12 long value; 13 struct node *next; 14 }*d[maxn+1],*e[maxn+1]; 15 16 int main() 17 { 18 struct node *p; 19 long n,m,i,x,y; 20 scanf("%ld%ld",&n,&m); 21 for (i=1;i<=n;i++) 22 { 23 d[i]=(struct node *) malloc (sizeof(struct node)); 24 e[i]=d[i]; 25 } 26 27 //点在链表的顺序与输入的顺序相反 28 for (i=1;i<=m;i++) 29 { 30 scanf("%ld%ld",&x,&y); 31 //to point x 32 ///新创一个内存空间,p指针指向这个内存空间(结构体) 33 p=(struct node *) malloc (sizeof(struct node)); 34 ///在记录与x相邻的结点的链表的末端加入数值, 35 ///并且末端与一个新的结构体指针连接,使当前末端为一个结构体指针 36 e[x]->value=y; 37 e[x]->next=p; 38 e[x]=p; 39 //to point y 40 //Don‘t forget initialization 41 p=(struct node *) malloc (sizeof(struct node)); 42 e[y]->value=x; 43 e[y]->next=p; 44 e[y]=p; 45 } 46 for (i=1;i<=n;i++) 47 { 48 printf("Point %ld:",i); 49 p=d[i]; 50 ///末端为一个结构体指针 51 while (p!=e[i]) 52 { 53 printf(" %ld",p->value); 54 p=p->next; 55 } 56 printf("\n"); 57 } 58 return 0; 59 } 60 /* 61 Input: 62 6 9 63 1 2 64 1 3 65 1 4 66 2 5 67 3 4 68 3 5 69 3 6 70 4 6 71 5 6 72 Output: 73 Point 1: 2 3 4 74 Point 2: 1 5 75 Point 3: 1 4 5 6 76 Point 4: 1 3 6 77 Point 5: 2 3 6 78 Point 6: 3 4 5 79 */
原文:http://www.cnblogs.com/cmyg/p/6911045.html