The linked list is one of the most basic data structures, and the steps to create a single necklace are as follows
- Defining a linked list node
- Defines three pointers--the head pointer, the tail pointer, and the current node pointer. and separately request memory, initialize
- The judge is not the head pointer, if it is, then the current node is assigned to the head pointer, the trailing pointer is null, if the current is not the head pointer, append the current node after the tail pointer
- After the insert operation is completed, update the successor of the tail and tail pointers
- Re-apply a piece of memory for the new extension node to use
Define a simple node structure body
1 struct Node 2 {3 int data; 4 struct Node *Next; 5 } Node;
Finally returns the head pointer of the linked list
1Node *Create ()2 {3 intN;4 inti;5Node *head=NULL;6Node *tail;7Node *p;8Tail = (Node *)malloc(sizeof(Node));9p = (Node *)malloc(sizeof(Node));Ten if(p==NULL) One { Aprintf"Fail to create a new node ....."); - returnNULL; - } the Else - { - for(i=0; i<Ten; i++) - { +P->data=i; - if(head==NULL) + { AHead=p; attail->next=NULL; - } - Else - { -tail->next=p; - } inTail=p; -tail->next=NULL; top = (Node *)malloc(sizeof(Node)); + } - } the returnhead; *}
Problem
The first time the linked list is written, the value of the tail node is always output each time the linked list is output. Later found that the original is a pointer to the problem.
Is that each time a node is added, not a new request for a piece of unused memory, but continue to use P, and P and head are pointing to the head node (line 22nd), so the use of P and head can change the value of the head node, so each time you change p, it actually changes the value pointed by the head.
Therefore, a new memory should be requested for the new node .
Establishment of a single necklace table