链表的数组实现

#include <iostream>
using namespace std;

#define MAXSIZE 100

/*
链表的数组实现
*/
typedef struct
{
    int listData[MAXSIZE];
    int last;
}List, *pList;

pList CreateEmptyList()
{
    pList pL;
    pL = new List;
    pL->last = -1;
    return pL;
}

int FindListElement(int X, pList pL)
{
    int i = 0;
    while ( i <= pL->last && pL->listData[i] != X )
    {
        i++;
    }
    if (i > pL->last)
    {
        return -1;    //链表中找不到对应元素
    }
    else
    {
        return i;
    }
}

void InsertListElement(int X, int position, pList pL)
{
    int i;
    if ( pL->last == MAXSIZE - 1 )
    {
        cout << "List Full!" << endl;
        return;
    }
    if ( position < 1 || position > pL->last + 2 )    //链表起始位置数组从1开始,last为当前数组下标从0开始(last = -1代表链表为空)
                                                    //last + 2为在链表尾部添加一个元素(不影响链表中已经存在的元素)
    {
        cout << "Error Position!" << endl;
        return;
    }
    for ( i = pL->last; i >= position - 1; i++)    //将元素插入位置position之前
    {
        pL->listData[i + 1] = pL->listData[i];
    }
    pL->listData[position - 1] = X;
    pL->last++;
    return;
}

void DeleteListElement(int position, pList pL)    //position为第K个元素
{
    int i;
    if ( position < 1 || position > pL->last + 1 )
    {
        cout << "Error Position!" << endl;
        return;
    }
    for ( i = position - 1; i < pL->last ; i++)
    {
        pL->listData[i] = pL->listData[i + 1];
    }
    pL->last--;
    return;
}
原文地址:https://www.cnblogs.com/liangchao/p/4274969.html