zoukankan      html  css  js  c++  java
  • 7.5_链表_添加元素_尾插法/头插法

    尾插法:

    头插法:

     

     #include <stdio.h>
    #include <stdlib.h>
    //
    尾插法 & 头插法 //用数组中的元素填充结点数据域 //结点 struct linkNode{ int data; struct linkNode *next; }; void output(struct linkNode *head); //打印链表数据域 struct linkNode *creat_link_list_rear(int *a, int n); //尾插法 struct linkNode *creat_link_list_head(int *a, int n); //头插法 int main() { int a[6]; //存放结点数据 struct linkNode *head_rear; //头指针(尾插法) struct linkNode *head_head; //头指针(头插法) printf("输入数组各元素的值【6个】: "); for(int i=0; i<6; i++){ scanf("%d", &a[i]); } //尾插法 head_rear = creat_link_list_rear(a, 6); printf("此链表各个节点的数据为: "); output(head_rear); //头插法 head_head = creat_link_list_head(a, 6); printf("此链表各个节点的数据为: "); output(head_head); return 0; } //尾插法 struct linkNode *creat_link_list_rear(int a[], int n){ struct linkNode *h = NULL; //新建链表h,将每个结点依次插入到链尾,将链表的头指针返回 struct linkNode *s; //s指向要插入的结点 struct linkNode *r; //r指向链表尾结点 for(int i=0; i<n; i++){ s = (struct linkNode *)malloc(sizeof(struct linkNode)); s->data = a[i]; s->next = NULL; if(h == NULL){ h = s; }else{ r->next = s; } r = s; //r指向当前链表的尾结点 } return h; //返回链表头指针 } //头插法 struct linkNode *creat_link_list_head(int a[], int n){ struct linkNode *h = NULL; struct linkNode *s; //s指向要插入的结点 for(int i=5; i>=0; i--){ s = (struct linkNode *)malloc(sizeof(struct linkNode)); s->data = a[i];
    s->next = NULL;
    if(h == NULL){
                h = s;
            }else{
                s->next = h;
                h = s;
            }
        }
    
        return h;
    }
    
    
    //打印链表数据
    void output(struct linkNode *head){
        struct linkNode *p = head;
    
        while (p){
            printf("%d ", p->data);
            p = p->next;
        }
    
        printf("
    ");
    }

  • 相关阅读:
    关于《Spark快速大数据分析》运行例子遇到的报错及解决
    把打印的内容保存成文件(PDF)
    浏览器升级提示网站:《快乐浏览》
    apache server-status配置
    Centos7安装完毕后联网-设置ip地址(VMware虚拟机)
    centos中apache自用常用额外配置记录(xwamp)
    ie浏览器升级的正确姿势
    有道云笔记web版本居然不支持火狐
    php 单文件测试代码时必加入的代码
    php简易配置函数
  • 原文地址:https://www.cnblogs.com/CPU-Easy/p/14053127.html
Copyright © 2011-2022 走看看