首页 > 代码库 > 线性表

线性表


顺序线性表:

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>

typedef int ElemType;             //声明新类型名
typedef struct List
{
    ElemType * elem;
    int length;
    int maxsize;
}Sqlist;
 
void Init_Sqlist(Sqlist &L)         // 构造空线性表
{
    L.elem = (ElemType *)malloc(100 * sizeof(ElemType));
    if(!L.elem)      exit(-1);
    L.maxsize = 100;
    L.length = 0;
}
 
void DestroyList(Sqlist &L)           // 销毁线性表
{
    if(L.elem)             free(L.elem);
}
 
int GetLength(Sqlist L)  
{
    return (L.length);
}
 
void GetElem(Sqlist L,int i,ElemType &e)                // 用e返回L中第i个元素的值
{
    if(i<0 || i>L.length)     e = -1;
    e = L.elem[i-1];
}
 
void SqlistInsert(Sqlist &L,int i,ElemType e)        //   插入 在L中第i个位置之前插入新的元素e,L的长度加1
{
    int j;
    if(i<1 ||i>L.length+1)          exit(-1);
    if(L.length >= L.maxsize){
        L.elem = (ElemType * ) realloc (L.elem, (10 + 100)* sizeof(ElemType));
        if(!L.elem)         exit(-1);
        L.maxsize += 10;
    }
    for(j = L.length;j>=i-1;j--)
    {
        L.elem[j+1]  = L.elem[j];
    }
    L.elem[j+1] = e;
    L.length += 1;
}
 
void SqlistDelete (Sqlist &L,int i,ElemType &e)      // 删除 在L中删除出第i个数据元素,并用e返回其值,L的长度减1
{
 int j;
 if((i<1)||(i>L.length))      exit(-1);
if(L.length>L.maxsize)
   {
    L.elem=(ElemType *) realloc (L.elem,10*sizeof(ElenType));
     if(!L.elem)  exit(-1);
     L.maxsize+=10;
   }
   for(j=L.length;j<=i-1;j--)
   {
    L.elem[j-1]=L.elem[j];
   }
   L.elem[j+1]=e;
     L.length -= 1;
}
void PrintSqList(Sqlist L)             //输出链表
{    int i;
    for(i = 0;i<L.length;i++)
    {
        printf("%d ",L.elem[i]);
    }
}
 
int main()
{
    Sqlist L;
    int e;
    Init_Sqlist(L);
    int i;
    for(i = 1;i<=5;i++)
    {
        scanf("%d",&e);
        SqlistInsert(L,i,e);
    }
    PrintSqList(L);
    return 0;
}



链式线性表:

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
 
typedef int ElemType;
typedef struct Node{
    ElemType data;
    struct Node * next;
}* Linklist;
 
void InitLinklist (Linklist &L){
    L = NULL;
}
 
void LinklistInsert1 (Linklist &L ,ElemType e)        //插入在链表的开头 (L为头指针)
{
    Linklist s ;
    s = (Linklist) malloc (sizeof(struct Node));
    s->data = http://www.mamicode.com/e;>