zoukankan      html  css  js  c++  java
  • 头插法建立单链表学习总结

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

    头插法是指每次将新节点插入头部(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);
        }
    }
  • 相关阅读:
    学生数据增删改查--顺序表
    应用3+2mvc第一次作业
    双色球随机选【代码】
    字符串穷举
    使用nuget发布自己的包
    VS CODE中配置JAVA格式化细节
    反射的理解(含一点xml)
    UdpClient实现udp消息收发
    c#背包问题代码
    利用TcpClient,简单的tcp消息收发
  • 原文地址:https://www.cnblogs.com/NDKY9/p/6803387.html
Copyright © 2011-2022 走看看