Static linked list is realized by array, is a sequential storage structure, is continuous in physical address, and needs to be pre allocated size. The dynamic linked list uses the memory application function (C is malloc,C + + is new) to dynamically apply for memory, so there is no limit on the length of the linked list. Because the dynamic linked list applies for memory dynamically, the physical address of each node is not continuous, and it needs to be accessed sequentially through pointers.
#define _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1 #include <stdio.h> #include <stdlib.h> /*All nodes are defined in the program, not opened temporarily, and cannot be released after use. This kind of list is called "static list".*/ struct Student { int num; float score; struct Student *next; }; int main() { struct Student stu1, stu2, stu3, *head, *p; stu1.num = 1001; stu1.score = 80; //Assign values to num and score members of stu1 node stu2.num = 1002; stu2.score = 85; //Assign values to num and score members of stu2 node stu3.num = 1003; stu3.score = 90; //Assign values to num and score members of stu3 node head = &stu1; //The head pointer points to the first node stu1 stu1.next = &stu2; //Assign the address of stu2 node to the next member of stu1 node stu2.next = &stu3; //Assign the address of stu3 node to the next member of stu2 node stu3.next = NULL; //Stu3 is the last node. The next member of stu3 does not store the address of any node. Set it to NULL p = head; //Make the p pointer also point to the first node //Traverse static list do{ printf("%d,%f\n", p->num, p->score); //Output the data of the node p points to p = p->next; //Then let p point to the next node } while (p != NULL); //Until the next member of p is NULL, the traversal is completed system("pause"); }
#define _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1 #include <stdio.h> #include <stdlib.h> /*The so-called dynamic linked list refers to the establishment of a linked list from scratch in the process of program execution, that is, to open up nodes and input data of each node one by one, and establish the relationship between the front and back links.*/ struct Student { int No;//Student ID struct Student *next; }; int main() { struct Student *p1, *p2, *head; int n = 0; //Node number head = NULL; p1 = (struct Student *)malloc(sizeof(struct Student)); printf("Please enter a student number\n"); scanf("%d", &p1->No); p2 = p1; //At the beginning, p1 and p2 both point to the first node while (p1->No != 0) { n++; if (n == 1) { head = p1; } else { p2->next = p1; } p2 = p1;//p2 is the last node printf("Please enter the student number and enter 0 to terminate:\n"); p1 = (struct Student *)malloc(sizeof(struct Student)); scanf("%d", &p1->No); }; p2->next = NULL;//After input, P2 - > next is NULL //Traversal dynamic list struct Student *p; p = head; while (p != NULL) { printf("%d,", p->No); p = p -> next; } printf("\n"); system("pause"); }