Today, in the chain storage process of linear tables, I encountered a strange problem, that is, the same program, which can be smoothly executed using the for loop, however, using the while loop reminds me that "the Node space application failed !!! ", I had no clue for a whole morning. Record this issue and continue exploring it later.
The following describes how to create a single-chain table using a For Loop:
// Create the listnode * creatlistl (int n, datatype * X) {listnode * head, * P1, * P2; int I; head = (listnode *) malloc (sizeof (listnode); If (Head = NULL) {printf ("Node space application failed !!! \ N "); return NULL;} p1 = head; for (I = 0; I <n; I ++) {P2 = (listnode *) malloc (sizeof (listnode); If (P2 = NULL) {printf ("Node space application failed !!! \ N "); return NULL;} P2-> DATA = * (x + I); P1-> next = P2; P1 = P2;} P1-> next = NULL; return head ;}
The following describes how to create a single-chain table using a while loop:
// Create a single-chain table 2 listnode * creatlistl (int n, datatype * X) 3 {4 listnode * head, * P1, * P2; 5 Int I = 0; 6 head = (listnode *) malloc (sizeof (listnode); 7 if (Head = NULL) {8 printf ("Node space application failed !!! \ N "); 9 return NULL; 10} 11 p1 = head; 12 while (I <n) {13 P2 = (listnode *) malloc (sizeof (listnode )); 14 if (P2 = NULL) {15 printf ("Node space application failed !!! \ N "); 16 return NULL; 17} 18 P2-> DATA = * (x + I); 19 P1-> next = P2; 20 p1 = P2;
I ++; 21} 22 P1-> next = NULL; 23 return head; 24}
For Loop and WHILE LOOP