Two ways to create a linked list in C language (head insertion method and tail insertion method)

Title C language to create a linked list in two ways (head interpolation and tail interpolation)

……Not much explanation, all in the code comments
1. Header insertion

//头插法创建链表
#include<bits/stdc++.h>
using namespace std;
typedef struct node
{
    
    
    int data;
    struct node *next;
}Node;
int main()
{
    
    
    Node *head,*p,*q,*t;
    head=(Node*)malloc(sizeof(Node));//创建头结点
    head->next=NULL;//初始化为空链表
    int a,n;//要输入的数以及要创建的结点个数
    cin>>n;
    for(int i=1;i<=n;i++)
    {
    
    
        cin>>a;
        p=(Node *)malloc(sizeof(Node));
        p->data=a;;
        p->next=head->next;//头插法类似于插入排序,将原本头结点指向的内容赋值给要插入的结点的后继指针
        head->next=p;//再使得头结点指向要插入的结点
        //每一次新插入的结点都在头结点的后面,所以输出顺序和输入顺序是逆序
    }
    t=head->next;//从首结点处开始遍历
    while(t!=NULL)
    {
    
    
        cout<<t->data<<" ";
        t=t->next;
    }
    cout<<endl;
}

operation result:
Insert picture description here

2. Tail insertion method

//尾插法创建链表
#include<bits/stdc++.h>
using namespace std;
typedef struct node
{
    
    
    int data;
    struct node *next;
}Node;
int main()
{
    
    
    Node *head,*p,*q,*t;
    head=(Node*)malloc(sizeof(Node));//创建头结点
    head->next=NULL;//初始化为空链表
    int a,n;//要输入的数以及要创建的结点个数
    cin>>n;
    for(int i=1;i<=n;i++)
    {
    
    
        cin>>a;
        //动态申请一个空间用于存放结点
        p=(Node*)malloc(sizeof(Node));
        p->data=a;;
        p->next=NULL;//设置当前结点的下一个结点为空
        if(head->next==NULL)
        head->next=p;//如果这是第一个创建的结点,则将头结点的后继指针指向当前结点
        else
            q->next=p;//如果不是,则将上一个结点的后继指针指向当前结点
        q=p;//指针q也必须指向当前结点,尾插法的关键
    }
    t=head->next;//从首节点处开始遍历输出
    while(t!=NULL)
    {
    
    
        cout<<t->data<<" ";
        t=t->next;
    }
    cout<<endl;
}

Operation results
Insert picture description here
If there are any errors or needs to be improved in the above content, you are welcome to raise them in the comment area and make progress together. ( )

Guess you like

Origin blog.csdn.net/weixin_53017755/article/details/114182037