zoukankan      html  css  js  c++  java
  • 04 把 list2 依次尾插入到 list1 中

     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 #define Capacity1 10
     4 #define Capacity2 5
     5 struct List {
     6     int* ElemSet;
     7     int len;
     8     int capacity;
     9 }list1,list2;
    10 
    11 void initList() {
    12     list1.len = 0, list2.len = 0;
    13     list1.capacity = 10;
    14     list2.capacity = 5;
    15     list1.ElemSet = (int*)malloc(Capacity1 * sizeof(int));
    16     list2.ElemSet = (int*)malloc(Capacity2 * sizeof(int));
    17 
    18     if (!list1.ElemSet || !list2.ElemSet) {
    19         printf("初始化失败
    ");
    20         return;
    21     }
    22     else {
    23         printf("成功创建list1和list2
    ");
    24         //给list1初始化5个数据
    25         for (int i = 0;i < 5;i++) {
    26             list1.ElemSet[i] = i + 1; //1,2,3,4,5
    27             list1.len++;
    28         }
    29         //给list2初始化5个数据
    30         for (int i = 0;i < 5;i++) {
    31             list2.ElemSet[i] = i + 10; //11,12,13,14,15
    32             list2.len++;
    33         }
    34     }
    35 }
    36 
    37 //打印表中数据
    38 void showList(struct List list) {
    39     for (int i = 0;i < list.len;i++) {
    40         printf("%d  ", list.ElemSet[i]);
    41     }
    42     printf("
    ");
    43 }
    44 
    45 //在表中插入元素
    46 void insertElem(struct List list, int e, int insertIndex) {
    47     for (int i = list.len - 1;i >= insertIndex;i--) {
    48         list.ElemSet[i + 1] = list.ElemSet[i];
    49         //showList(list);
    50     }
    51     list.ElemSet[insertIndex] = e;
    52 }
    53 
    54 //把list2全部插入到list1中
    55 void unionList() {
    56     for (int i = 0;i < list2.len;i++) {
    57         list1.len++;
    58         insertElem(list1, list2.ElemSet[i], list1.len-1 );//注意:总是插入到list1中的最后一个位置,即list1.len-1的位置,list1.len是不段改变的
    59         //showList(list1);
    60     }
    61     showList(list1);
    62     printf("表的长度是:%d
    ", list1.len);
    63 }
    64 
    65 void main() {
    66     initList();
    67     printf("表1的数据是:
    ");
    68     showList(list1);
    69     printf("表2的数据是:
    ");
    70     showList(list2);
    71     printf("把list2插入到list1后:
    ");
    72     unionList();
    73 }

  • 相关阅读:
    [剑指offer] 赋值运算符重载
    [hihoCoder] 股票价格
    [LintCode] Kth Smallest Number in Sorted Matrix
    [LeetCode] Subarray Sum Equals K | 前缀和+哈希表
    [LeetCode] Add and Search Word
    [LeetCode] Implement Trie
    Tableau基础练习(三)
    Tableau基础练习(二)
    Tableau基础练习(一)
    SpringMVC用户请求下载文件
  • 原文地址:https://www.cnblogs.com/shanlu0000/p/12411782.html
Copyright © 2011-2022 走看看