zoukankan      html  css  js  c++  java
  • 数据结构实验1

    题目1:创建一个顺序表,存放在数组 A[N]中,元素的类型为整型,设计算法调整 A,使其左边的所有元素小于 0,右边的所有元素大于 0(要求算法的时间复杂度和空 间复杂度均为 O(n))。

    move.c

    #include "move.h"

    int main()
    {
    int a[10]={-1,2,4,-5,6,8,-9,2 ,-2,-6},i;
    SequenList *A; //定义一个指针
    A=Init_SequenList( );
    for(i=0;i<10;i++)
    Insert_SequenList(A,a[i],i+1);
    Print_SequenList(A);
    printf(" 调整后: ");
    quickSwapList(A);
    Print_SequenList(A);


    return 0;
    }

    move.h

    #ifndef SEQL
    #define SEQL
    #include <stdio.h>
    #include <stdlib.h>

    typedef int elemtype; /*假定线性表元素的类型为整型*/

    #define MAXSIZE 20 /*假定线性表的最大长度为1024*/
    typedef struct
    { elemtype data[MAXSIZE];
    /*定义线性表数组,第一个结点是data[0] */
    int last; /*记录线性表中最后一个元素在数组中的位置*/
    } SequenList,*SQL;
    //顺序表的初始化
    SequenList * Init_SequenList( )
    { SequenList *L;
    L = (SequenList *) malloc ( sizeof( SequenList ) );
    L->last = -1;
    return L;
    }

    int Insert_SequenList(SequenList *L, elemtype x, int i )
    /*在顺序表中指定的位置插入值为x的结点,L是SequenList类型的指针变量*/
    /* x是待插入结点的数据元素值,i 是在顺序表中的插入位置*/
    { int j;
    if ( L->last >= MAXSIZE - 1 ) /*表满?*/
    { return 0; }
    if( i < 1 || i > L->last + 2 ) /*插入位置非法?*/
    { return -1; }
    for( j = L->last; j >= i - 1; j --) /*1. 移动*/
    L->data[j + 1] = L->data[j];
    L->data[ i - 1] = x; /*2. 插入*/
    L->last = L->last + 1; /*3. 表长+1*/
    return 1; /*插入成功,函数返回1*/
    }
    int Delete_SequenList(SequenList *L, int i)
    { int j;
    if ( i < 1 || i > L->last + 1 )
    {
    return 0;
    }
    else
    { for( j = i; j <= L->last; j ++)
    L->data[j - 1] = L->data[j];
    L->last --; }
    return 1;
    }
    void Print_SequenList(SequenList *L) /*顺序表遍历算法*/
    { int i;
    for ( i = 0; i <= L->last; i ++ )
    { printf("a[%2d] = %4d ", i + 1,L->data[i] );
    if ((i + 1)%5 == 0)
    printf(" ");
    }
    }

    /*左负右正*/
    void quickSwapList(SequenList *A)
    {
    int i=0,j=A->last;
    int temp;
    while(i<j)
    {
    while(i<j&&A->data[i]<0)
    i++;
    while(i<j&&A->data[j]>=0)
    j--;
    if(i<j)
    {
    temp=A->data[i];
    A->data[i]=A->data[j];
    A->data[j]=temp;
    }
    i++;
    j--;
    }
    }

    #endif

  • 相关阅读:
    J2EE学习笔记:Filter
    J2EE学习笔记:HTTP协议
    J2EE学习笔记:JSP
    Hibernate 笔记(二) 数据关系
    top命令总结
    让gdb能打印C++中的容器类型
    ps命令注意事项
    自己动手写一个自动登录脚本gg
    request 中url拼接排序参数与签名算法
    python3.7 AES.MODE_ECB(128位) pkcs5padding 加密算法
  • 原文地址:https://www.cnblogs.com/wuyibb/p/6793349.html
Copyright © 2011-2022 走看看