头插法建立单链表学习总结

单链表是一种链式存储的数据结构,每一个节点存放数据和指向下一个节点的指针。

头插法是指每次将新节点插入头部(head节点之后),最终链表顺序与插入顺序相反。

这就好比你在食堂排队,大妈所在窗口是头部,每次都有人插入到队伍最前面,结果你是最后买到饭的。

图解:

以下代码是新建链表并遍历输出元素

#include<stdio.h>
#include<stdlib.h>

typedef struct _node{
    int data;
    struct _node *next;
}node;

node *headinsert(int n);//创建链表并插入新节点 
void output(node *head);//遍历链表并输出节点数据 
void destroy(node *head);//清除链表 

int main(){
    int n;
    node *head;
    
    scanf("%d",&n);
    head=headinsert(n);
    output(head);
    destroy(head);
    return 0;
}
node *headinsert(int n){
    node *head,*q;
    
    head=(node *)malloc(sizeof(node));//malloc返回void* 需要强制转换类型 
    head->next=NULL;
    for(int i=0;i<n;i++){                //申请新节点并插入链表 
        q=(node *)malloc(sizeof(node));
        scanf("%d",&q->data);
        q->next=head->next;    
        head->next=q;
    }
    return head;
}

void output(node *head){
    node *q;            //新建指针q使其从头节点遍历链表 
    q=head;
    while(q->next!=NULL){
        q=q->next;
        printf("%d ",q->data);
    }
}

void destroy(node *head){
    node *q,*p;
    for(p=head;p;p=q){
        q=p->next;
        free(p);
    }
}
原文地址:https://www.cnblogs.com/NDKY9/p/6803387.html