用結構體指針存儲數據__正序_逆序下的輸入
阿新 • • 發佈:2017-05-27
scan point 內存 initial return pri tdi log 位置
逆序輸入
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(structnode)); 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 */
用結構體指針存儲數據__正序_逆序下的輸入