#include <stdio.h> #include <malloc.h> #include <stdlib.h>typedef struct node{int date;//data domain struct node* pnext;//pointer field}node,*pnode;//function declaration; Pnode create_list (void); void Travel_list (Pnode phead); int main () {Pnode phead= null;//is equivalent to struct node* phead=null;phead = create_list ();//create a non-circular linked list and point to Phead;travel_list (Phead) The head node address of the list;// Traverse the linked list return 0;} Pnode create_list (void) {int len;//is used to hold a valid node int i;//used to loop int val;//The value of the node used to temporarily hold user input pnode Phead = (pnode) malloc (sizeof ( NODE), if (null==phead) {printf ("Allocation failed, program terminates!\n");//return 0;exit (-1);} Pnode ptail=phead;//causes Ptail to always point to the tail node. ptail->pnext=null;printf ("Please enter the number of linked list nodes you need to generate; len="), scanf ("%d", &len), and for (i=0;i<len;i++)//For Len nodes. {printf ("Enter the value of%d nodes:", i+1); scanf ("%d", &val); Pnode pnew = (pnode) malloc (sizeof (NODE));//defines a pointer type that holds a pointer to the new address, pointing to the next bit of the tail pointer. if (null==pnew) {printf ("Allocation failed, program terminated \ n"); exit (-1);} pnew->date=val;//the value of the input is equal to a newly allocated storage unit in addition to the unit. The next node of the ptail->pnext=pnew;//tail pointer is a pointer to the new address stored by pnewpnew->pnext=null;//pnew, which is empty ptail=pnew;//the last allocated storage unit is the tail pointer. }returnPhead;} void Travel_list (Pnode phead)//The function that traverses the node {pnode p=phead->pnext;//defines a p-pointer that iterates through the nodes in the list. First assign the first node to P;while (null!=p) {printf ("%d", p->date);p =p->pnext;//If the node that P points to is not empty, then it continues to point to the next node, and if it is empty, the program ends up running. }printf ("\ n"); return;}
Creation and traversal of linked lists