当前位置: 代码迷 >> C语言 >> 插入顺序表的问题
  详细解决方案

插入顺序表的问题

热度:423   发布时间:2005-09-06 17:37:00.0
插入顺序表的问题
#include<stdio.h>
#define ADDLIST 10;
#define LIST_INIT_SIZE   100
typedef struct
{
        int *p;
        int length;
        int listsize;
}SqList;
void creatSqList(SqList **r,int n)
{
     int i;
     r->p =(int *)malloc(LIST_INIT_SIZE*sizeof(int));
     if(!r->p) exit(0);  //fail to assign storage
     r->length = 0;
     r->listsize = LIST_INIT_SIZE; //size(at the begin)
     for(i=0;i<n;i++)
     {
       printf("输入第%d个值:",i);
       scanf("%d",r->p);
     }
}
int findInsertPlace(SqList **r,int x)
{
    int i=0;
    while(i<r->length&&*(r->p)<x)
        (r->p)++;
    if(i>=r->length)
    printf("找不到插入的位置!请检查您的数据.");
    else
    return i;
}
void insert(SqList **r,int insertValue,int i)
{   
     int *end,*insert;  // end point to the end adress
     if(i<1||i>(r->length)+1)
     {
       printf("i值不合法!");
       exit(0);
     }
     if((r->length)>=(r->listsize))
     {
       insert = (int *)realloc(r->p,(r->listsize+ADDLIST)*sizeof(int));
       r->p = insert;
       r->listsize += ADDLIST;
     }
     insert = r->(p+i-1);  //insert是插入的位置
     for(end = r->p+(r->length-1);end>=insert;--end)// end point to the end adress
       *(end+1) = *insert;
       *insert = insertValue;
       (r->length)++;
}
void outputSqList(SqList **r)
{
     for(;(r->p)<r->(p+(r->length-1));(r->p)++;)
       printf("%d",r->p);         
}
//此例子只能输入递增的元素
int main()
{
      SqList *r;
      int n = 4; // size
      int x =  4;//value
      creatSqList(&r,n); //n是线性顺序表的长度
      insert(&r,x,findInsertPlace(SqList &r,int x)); //x是要插入的值
       outputSqList(&r);
      system("pause");
      return 0;
}

[此贴子已经被作者于2005-9-6 18:04:39编辑过]


搜索更多相关的解决方案: 顺序  

----------------解决方案--------------------------------------------------------
唉,怎么说你呢,建议回去猛啃指针,特别是函数传递指针的问题。
----------------解决方案--------------------------------------------------------
  相关解决方案