Troubled for a long time the data structure to pick up, refer to the blog Daniel's article, think out a bit of their own understanding, hope to learn the data structure on the way of the brothers and sisters to help, but also for their home to clear ideas. Nonsense not much to say, directly on the code.
The required header files are as follows and the security warning is masked:
#define _crt_secure_no_warnings#include<stdio.h> #include <stdlib.h> #include <malloc.h>
The data type of the linked list is declared first, and is used in the following ways:
struct ListNode { int data; // data fields, storing data struct listnode* Next; // point to Next list node } Node, *pnode;
Here are two points to note: 1, if it is a CPP file, struct ListNode * Next can be written as listnode* Next;2, where the macro typedef keyword is used, node and Pnode are the newly declared data type names, Similar to existing int,char,double and so on. node is a struct type, pnode is a struct pointer type, if you need to understand the structure of the body to step into another article.
Next look at the linked list to create the function definition
Pnode CreateList (void) { intLen//used to define the chain table length intVal//for storing node valuesPnode Phead = (pnode)malloc(sizeof(Node));//Create a memory space that allocates a head node//the head node corresponds to the Sentinel of the list, does not store the data, and points to the first node (the first node) if(Phead = = NULL)//determine if the assignment was successful{printf ("space allocation failed \ n"); Exit (-1); } //a pointer to the tail of the list, which the individual thinks ptail is on the stack space, is a secondary pointer to connect to the new nodePnode ptail = Phead;//the end node of the linked list, initially pointing to the head nodePtail->next = NULL;//The last node pointer is set to NULLprintf"Please enter the number of nodes:"); scanf ("%d", &len);//number of input nodes for(inti =0; i < Len; i++) {Pnode pnew= (Pnode)malloc(sizeof(Node));//Assigning a new node if(Pnew = =NULL) {printf ("failed to allocate new node \ n"); Exit (-1); } printf ("Please enter data for%d nodes:", i +1); scanf_s ("%d", &val);//enter data for the linked list nodepnew->element = val;//assigning data to a node data fieldPtail->next = pnew;//The end node pointer points to the next new node, connecting the new nodePnew->next = NULL;//The new node pointer is pointing to an emptyPtail = pnew;//Copy the new node to the end node and point the Ptail to the tail node} printf ("create linked list succeeded \ n" ); returnPhead;//return to head node}
Last look at the main function
int Main () { = CreateList (); // Create a pointer to the head of the newly created linked list return 0 ;}
A linked list of data-C + + structures (single-linked list is disassembled in one step)