線性表 | 數組

頭文件

#ifndef _SQLIST_FUNC_H_
#define _SQLIST_FUNC_H_

#define MAXSIZE 20
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0

typedef int ElemType;
typedef int status;

//線性表
typedef struct
{
    ElemType data[MAXSIZE];
    int      length;
    int      size ;
}sqlist;

//函數聲明
status get_element(sqlist l,int i,ElemType *e);
status insert_element(sqlist *l,int i,ElemType e);
status delete_element(sqlist *l,int i,ElemType *e);

#endif

功能函數

  • 獲取元素
/*func:Gets the linear table element.
  para:
        l:linear table
        i:Get the i element
        e:Use e return element
  return:
        success:OK
        fail:ERROR
*/
status get_element(sqlist l,int i,ElemType *e)
{
    if(l.length == 0 || i < 1 || i > l.length)
    {
        return ERROR;
    }

    *e = l.data[i-1];

    return OK;
}
  • 在某個位置插入元素
/*func:Inserts an element into a linear table before i position.
  para:
        l:linear table
        i:Insertion position.
        e:The element to be inserted.
  return:
        success:OK
        fail:ERROR
*/
status insert_element(sqlist *l,int i,ElemType e)
{
    int                 k = 0;

    if(!l || l->length >= l->size || i > l->size || i < 1)
    {
        return ERROR;
    }

    for(k = l->length-1;k >= i-1;k--)
    {
        l->data[k+1] = l->data[k];
    }
    l->data[i-1] = e;
    l->length++;
    return OK;
}
  • 刪除某個元素
/*func:Delete an element into a linear table.
  para:
        l:linear table
        i:delete position.
        e:The element to be deleted.
  return:
        success:OK
        fail:ERROR
*/
status delete_element(sqlist *l,int i,ElemType *e)
{
    int                 k = 0;
    if(!l || i < 1 || i > l->length)
    {
        return ERROR;
    }

    *e = l->data[i-1];
    for(k = i-1;k < l->length;k++)
    {
        l->data[k] = l->data[k+1];
    }
    l->length--;

    return  OK;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章