zoukankan      html  css  js  c++  java
  • SWUST OJ (943)

      顺序表插入操作的实现

     1 #include<stdio.h>
     2 #include <stdlib.h>
     3 
     4 void InitList(int *&l, int n)
     5 {
     6     l = (int*)malloc(n*sizeof(int));
     7 }
     8 
     9 void CreateList(int *&L,int n,int *array)
    10 {
    11     int *c = L;
    12     while(n--)
    13     {
    14         *c++ = *array++;
    15     }
    16 }
    17 
    18 void InsertList(int *&l,int n,int item, int data)
    19 {
    20     int flag = n;
    21     for(int i=0;i<n;i++)
    22     {
    23         if (l[i]==item)
    24         {
    25             flag = i;
    26         }
    27     }
    28 
    29     /*
    30         c库函数 void *realloc(void *ptr, size_t size) 尝试重新调整之前调用 malloc 或 calloc 所分配的 ptr 所指向的内存块的大小。
    31         该函数返回一个指针指向重新分配大小的内存;
    32         ptr -- 指针指向一个要重新分配内存的内存块,该内存块之前是通过调用 malloc、calloc 或 realloc 进行分配内存的。如果为空指针,
    33         则会分配一个新的内存块,且函数返回一个指向它的指针。
    34         size -- 内存块的新的大小,以字节为单位。如果大小为 0,且 ptr 指向一个已存在的内存块,则 ptr 所指向的内存块会被释放,并返回一个空指针。
    35     */
    36     int *newbase =(int*)realloc(l,(n+1)*sizeof(int)); 
    37     l = newbase;
    38 
    39     if (flag!=n) 
    40     {
    41         int *q = &(l[flag]);
    42         for(int *p = &(l[n-1]); p>=q; p--)
    43         {
    44             *(p+1) = *p;
    45         }
    46         *q = data;
    47     }
    48     else
    49     {
    50         int *p = &(l[n]);
    51         *p = data;
    52     }
    53 }
    54 
    55 void DisList(int *b,int n)
    56 {
    57     while(n--)
    58     {
    59         printf("%d ",*b++);
    60     }
    61 }
    62 
    63 int main(int argc, char const *argv[])
    64 {
    65     /*int n = 10;
    66     int array[] = {10,20,30,40,50,60,70,80,90,100};
    67     int item = 50;
    68     int data = 55;*/
    69 
    70     int n,item,data;
    71     int *array;
    72     scanf("%d",&n);
    73     array = (int*)malloc(n*sizeof(int));
    74     for (int i = 0; i < n; ++i)
    75     {
    76         scanf("%d",&array[i]);
    77     }
    78 
    79     scanf("%d",&item);
    80     scanf("%d",&data);
    81 
    82     int *l;
    83     InitList(l,n);
    84     CreateList(l,n,array);
    85     InsertList(l,n,item,data);
    86     DisList(l,n+1);
    87     return 0;
    88 }
  • 相关阅读:
    【今日CV 视觉论文速览】 19 Nov 2018
    【numpy求和】numpy.sum()求和
    【今日CV 视觉论文速览】16 Nov 2018
    【今日CV 视觉论文速览】15 Nov 2018
    poj 2454 Jersey Politics 随机化
    poj 3318 Matrix Multiplication 随机化算法
    hdu 3400 Line belt 三分法
    poj 3301 Texas Trip 三分法
    poj 2976 Dropping tests 0/1分数规划
    poj 3440 Coin Toss 概率问题
  • 原文地址:https://www.cnblogs.com/Ghost4C-QH/p/10452832.html
Copyright © 2011-2022 走看看