顺序表排重

来源:互联网 发布:中国石油进出口数据 编辑:程序博客网 时间:2024/05/21 07:56
#include<stdio.h>#include<stdlib.h>#define LIST_INIT_SIZE   10 //初始分配量#define LISTINCREMENT   5  //分配增量typedef int ElemType;typedef  struct{    ElemType *elem;//存储空间基址    int length; //当前长度    int ListSize; //当前分配的存储} sqlist;int ListInsert_sq(sqlist &l, int i, int e)//增{    //线性表l第i个位置前插入e    //从i起到最后一个向后移一位,注意先从最后一个开始移    ElemType *p, *q;    if(i < 1 || i > l.length + 1)//插入位置有误        return 0;    if(l.length >= l.ListSize)//存储空间已满,增加空间    {        ElemType *newelem = (ElemType *)realloc(l.elem,(l.ListSize+LISTINCREMENT) * sizeof(ElemType));        if(!newelem)        {            exit(0);        }        l.elem = newelem;//更新基址        l.ListSize += LISTINCREMENT;//更新分配量    }    q = &(l.elem[i-1]); //q是插入位置    for(p = &(l.elem[l.length-1]); p >= q; p--)    {        *(p+1) = *(p);    }    *q = e;    l.length++;    return 1;}int InitList_sq(sqlist *l)  /*initial the list l*///形参是一个结构体指针{  l->elem=(ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));//初始化十个int容量  if(!l->elem) // if l->elem == NULL 前面有个!就代表if里的值为true   {      printf("无法分配空间!");      return 1;   }  else   {      l->length=0;//当前长度置为0      l->ListSize=LIST_INIT_SIZE;      //printf("ok\n");      return 0;   }}void show(sqlist &l)//显示{    for(int i = 0; i < l.length; i++)    {        printf("%d ",l.elem[i]);    }    printf("\n");}void Delete_Repeat(sqlist &l){    int count = 0;    int i;    for(i = 1; i < l.length && count+1<l.length;)    {        if(l.elem[count] == l.elem[count+1])        {            for(int j = count; j < l.length - 1; j++)            {                l.elem[j] = l.elem[j+1];            }            printf("\n移动");            l.length--;            show(l);            printf("count = %d\n",count);            count = 0;        }        else if(l.elem[count] != l.elem[count+1])        {            count++;        }    }}int main(){    sqlist L;    int e, i;    InitList_sq(&L);    for(i = 1; i <= 5; i++)    {        scanf("%d",&e);        ListInsert_sq(L,i,e);    }    show(L);    Delete_Repeat(L);    show(L);    return 0;}
0 0
原创粉丝点击