Build a singly linked list with C language

Let life be beautiful like summer flowers and death like autumn leaves. Life is as brilliant as summer flowers, and death is as quiet and beautiful as autumn leaves.

The linked list is linked to the data structure. You can get to know it first. You don't have to understand it, but it's OK to understand it. Before learning the linked list, you must understand the structure, as well as pointers. The foundation must be firmly laid, otherwise it will be difficult to learn data structures later.
mission details

Create a singly linked list with the lead node.

Related knowledge
What is a linked list? Linked list and binary tree are the foundation and core of C language data structure.

There are many forms of linked lists, it can be single-linked or double-linked, it can be sorted or unsorted, it can be cyclic or acyclic.

A singly linked
list (single linked list) is a kind of linked list. Its characteristic is that the link direction of the linked list is one-way. The access to the linked list starts from the head through sequential reading. The linked list is a list constructed using pointers. It is also called a node list, because the linked list is assembled by nodes, and each node has a pointer member variable to point to the next node in the list.

The list is composed of nodes, the head pointer points to the first node that becomes the head of the table, and ends at the last pointer to nuLL.

Source code:

#include <stdio.h>
#include <stdlib.h>
typedef struct node {
    
    
    int data;
    struct node *next;
}Node;

Node *CreatList(void)
{
    
    
    int val, i, n;
    Node *phead, *p, *q;
    phead = (Node *)malloc(sizeof(Node));
    q=phead;
    q->next=NULL;
    scanf("%d", &n);
    for(i=0; i<n; ++i)
    {
    
    
        scanf("%d", &val);
        p = (Node *)malloc(sizeof(Node));
        p->data=val;
        q->next=p;
        p->next=NULL;
        q=p;
    }
    return phead;
}
//输出链表
void ShowList(Node *phead)
{
    
    
    Node *p;
    p = phead->next;
    while(p)
    {
    
    
        printf("%d ", p->data);
        p = p->next;
    }
    printf("\n");
}

int main(void)
{
    
    
    Node *phead;
    phead = CreatList();
    ShowList(phead);
    return 0;
}

operation result:
Insert picture description here

Guess you like

Origin blog.csdn.net/m0_46259251/article/details/106295126