C-write single-linked list creation, release, append (i.e. always add nodes at the last position)

Source: Internet
Author: User

Yesterday at the weekend to learn a few pointers to the knowledge, I was the pointer is the state of the indefinitely, after yesterday, I learned a pointer to the more profound I really give others lectures is a way to learn. In addition to the recent review of data structures, I found that my blog is not linked to the list of posts, so take advantage of this time to add an article.

Before we do that, let's talk about some of the basics I'm going to say:

Why is the ① function argument a double pointer?

Let's start by writing a program like this:

# include<stdio.h>
void Gai (int m)
{
m=5;
}
int main (void)
{
int a=1;
Gai (a);
printf ("%d\n", a);
return 0;
}

So we can tell that the value of output A is 1, why did I call the function, pass a in, and not become 5? that's the point . I conclude that the parameter m is just an assignment variable of argument A, and we all know that the memory unit is allocated when the function is called, and when the function call is finished, the parameters are taken out, so the above procedure can be understood as follows: Define a variable A, its value is 1, when a is passed into the Gai function as an argument, The system defines a variable m and assigns the value of a "1" to M, and then executes the m=5. So, to the end of the whole program, m=5,a=1, so the value of a does not change at all. So, in the main function, it is impossible to change the value of a variable by a function.

Next we'll modify the program:

# include<stdio.h>
void Gai (int * m)
{
*m=5;
}
int main (void)
{
int a=1;
Gai (&a);
printf ("%d\n", a);
return 0;
}

After running we can see that the "a" on this time becomes "5". So, we can summarize:

If a variable wants to pass a function to change its own value, passing itself as a parameter is unsuccessful, only passing the pointer (address) itself can achieve this effect.

So when we create a linked list, we pass a double pointer, which is why the argument is a double pointer.

Because I have not understood before, until I yesterday to learn younger brother learning Sister lectures, I just suddenly dawned, so I am also very stupid, so here to sum up, because I in other blogs, see there are quite a lot of people do not understand why is a double pointer, now hope that readers can understand.

② each variable has its own address in the memory unit

For the sake of understanding, I draw to tie it to a piece, although it may not be the same in the physical structure, but it is logically long, such as
int a=2;

int * p = &a;

So, as long as it is a variable, it will have its own address (pointer), even if it is a pointer variable.

Then, the pointer is used to save the address, only two parts, part of it comes with its own address, part of it is to save someone else's address

The ③ pointer is the address, the address is the pointer, the pointer type of the variable its value is used only to load pointers.

Why would I say that? Because before, yesterday, I so long, incredibly has been misunderstood, but also blame me too stupid haha. For example, define the node type

typedef struct N
{
int data; Data fields
struct n * Next; Pointer field
} Node;

Then Node * L; I always thought l was that long.

Originally NOT!!!  It's not!! Killed me, I have been entangled for a long time!!! It's so stupid, haha!! It turns out that I always have what type of pointer it looks like!!

No, actually what kind of pointer it is, what kind of address it has. Rather than grow like that, so l was actually long like this:

In short this pit, if you already will, can smile me, if also like me to drop the pit, hope to see here can timely pits. This huge big hole, hey, it's killing me. It's strange that I didn't learn pointers carefully before.

The above is today's preparatory knowledge, and then began to learn the simple operation of single-linked list. I will use the graph to combine, because I always emphasize the combination of graphs and code, so as to learn the data

Structure, so as to have an image of the data structure of the idea, of course, the great God is directly understand, I can not afford to Gao pan. I compare dishes, I dug up their own learning methods, hey.

Single linked list I used the structure of the head pointer and the head node.

This time the single-linked list operation may be somewhat different, but the principle is the same, or, the figure is understood, the code will understand;

/* Parameter: pointer to the head (double pointer) action: Initialize the linked list, so that the head pointer to a new          node, the new nodes is the head node */void inithead (node * *phead)//parameter: The head pointer, in fact, is also the copy function of the head pointer: Release the entire list */ void Free_list (node * phead)/* parameter: Head pointer, one value action: Append val*/void Append (node * phead,int val)/* parameter to the end of the list//parameters: Head pointer action: traverse the output list (skip over node) */ void Showlist (Node * phead)

(i) Initialize the list of links

void Inithead (Node * *phead)//Generate head node for linked list so that the head pointer points to the head node.
{
*phead = (node *) malloc (sizeof (node));
if (*phead = = NULL)
{
printf ("Header node allocation failed, program terminated!") \ n ");
Exit (-1);
}
(*phead)->next=null;
}

Defined inside the main function: Node * L = NULL; Defines a pointer to the node type, which is actually the head pointer of the entire list

Then call Inithead (&L);

The illustrations are as follows:

*phead = (node *) malloc (sizeof (node));

In fact, *phead is the value of the head pointer L, plus * is the value of the pointer, malloc will apply for a node, and then return to the first address of the node, in fact, this new generation of nodes is not a name, in order to facilitate

Understand, we call it the X plot as follows:

As for Phead? Haha, when this function is finished, it will be killed, so in the end, it only for others to make a wedding dress, but this is the meaning of its existence.

If a single pointer is passed, Phead points to the newly generated node as the pirate's head pointer, and after the function is finished, their state is: L still exists and nothing has changed. Phead, was killed, thoroughly the bottom of the no, as for the newly generated node, it is a solitary inside the storage area shivering, waiting for the person to point to it, so this is why to use double pointers for reasons. With a double pointer, L pointed to the newly generated node, and Phead was killed, happy.

(ii) Release of the linked list

void Free_list (Node * phead)//Release list
{
Node * p;
while (phead! = NULL)
{
p = phead;
Phead = phead->next;
Free (p);
p = NULL;
}
}

Because the new node generated in the list is malloc, it is used to reclaim it with free, and malloc and free are monogamous.

In this small program may not be free and there is no big problem, but later when the project is not recycled when the trouble, so form the habit of free.

The illustrations are as follows:

Then P becomes then free (p) is the node that points to p, that is, the head node in the diagram, to kill,

Phead is also killed after the function, and L only hold a head address but can not find anyone;

The figure here is only one of the first nodes when the release, but even if there are multiple nodes, it is the same practice, you can paint your own simulation, deepen the memory.

(iii) Appending elements to the end of the list

void Append (Node * phead,int val)
{
Node * R=PHEAD;
Node * pnew = (node *) malloc (sizeof (node)); To generate a new node
if (pnew = = NULL)
{
printf ("New node assignment failed, program terminated!") \ n ");
Exit (-1);
}
pnew->data=val;
pnew->next=null;

while (r->next! = NULL)//Let the tail pointer loop until the last node
{
r=r->next;
}

r->next=pnew;
R=pnew;

}

This code is too long, a little difficult to draw, I try to, as shown below:

Then define a pointer R and copy the Phead over.

To make it easier to understand, I called all the newly generated nodes x.

A pnew pointer is then defined to point to the newly generated node x, and then the value is assigned and set to NULL

Actually, Pnew-<data is x.data.

And then this line of code

while (r->next! = NULL)//Let the tail pointer loop until the last node
{
r=r->next;
}

This is for the R pointer to point to the last node,

Why is r->next! = NULL instead of r!=null; there is a difference here, because my method of appending is a post-interpolation method. In short, the code is written according to the diagram.

R->next is this

and R is this

So when judging, it should be judged by the next in the list, rather than judging R has no point to whom;

The next is the final link.

r->next=pnew;
R=pnew;

r->next=pnew;//Why do they point to pnew here, but the picture points to X? I don't understand that. Right, a pointer to a node, then this pointer is equivalent to this node

And then the last one

(iv) Traversing the output chain list

void Showlist (Node * phead)
{
phead=phead->next; Skip over node output
while (Phead!=null)
{
printf ("%d", phead->data);
phead=phead->next;
}
}

The last one will not draw, I believe you can read.

At this point, the whole article should be finished. Tut-tut, went to dinner.

Mistakes please comment below, we progress together.

Thank you ~

Forgot to post the complete code, test your own test, I here test results are correct

# include<stdio.h># include<stdlib.h>typedef struct n{int data;   Data domain struct n * next;    Pointer field} node;void inithead (node * *phead)//Generate head node for linked list so that the head pointer points to the head node {*phead = (node *) malloc (sizeof (node)); if (*phead = = NULL) {printf ("Header node allocation failed, program terminated!        \ n ");    Exit (-1); } (*phead)->next=null;}    void Free_list (node * phead)//Release list {node * p;        while (phead! = NULL) {p = phead;        Phead = phead->next;        Free (p);    p = NULL;    }}void Append (node * phead,int val) {node * r=phead;  Node * pnew = (node *) malloc (sizeof (node)); Generate new node if (pnew = = NULL) {printf ("New node assignment failed, program terminated!")        \ n ");    Exit (-1);    } pnew->data=val;    pnew->next=null;    while (r->next! = NULL)//Let the tail pointer loop until the last node {r=r->next;    } r->next=pnew; R=pnew;} void Showlist (Node * phead) {phead=phead->next;//Skip node output while (Phead!=null) {printf ("%d", phead->d        ATA); Phead=phead-> next;    }}int Main (void) {Node * L = NULL;    Inithead (&AMP;L);    Append (l,1);    Append (l,4);    Append (l,7);    Append (l,9);    Append (l,332);    Append (l,6);    Append (l,235);    Showlist (L);    Free_list (L);    L=null; return 0;}

  

C-write single-linked list creation, release, append (i.e. always add nodes at the last position)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.