- /*ListInsert(*L,i,e):在线性表L中的第i个位置插入新元素e,L的长度加1*/
- /*
- 顺序存储线性表的插入算法思路:
- 1。如果插入的位置不合理,抛出异常
- 2。如果线性表的长度大于数组的长度,则抛出异常或动态增加容量
- 3。从最后一个元素开始向前遍历到第i个位置,分别将他们都向后移动一个位置
- 4。将要插入元素填入位置i处
- 5。表长加1
- */
- #include <iostream>
- using namespace std;
- typedef int datatype;
- /*顺序线性表的存储结构*/
- #define MAXSIZE 100
- typedef struct
- {
- datatype data[MAXSIZE];
- int len;
- }SequenList;
- int insert(SequenList *L,int i,int e)
- {
- int j;
- if (i < 1 || i > L->len+1 || L->len >= MAXSIZE) /*判断位置i是否存在以及是否有空的*/
- {
- printf( "Error"); /*存储单元*/
- }
- else
- {
- /*for(j=(*L).len-1;j>=i-1;j--)*/
- for(j=L->len-1;j>=i-1;j--)
- {
- /*将要插入位置后数据元素向后移一位 */
- L->data[j+1]=L->data[j];
- }
- L->data[i-1]=e; /*将新元素插入*/
- L->len=L->len+1;
- }
- return 0;
- }
- int main(void)
- {
- int i,InsertData,InsertLocation;
- SequenList List;
- List.len=0;//终端节点下标
- for(i=0;i<5;i++)
- { /*随机生成5个数*/
- List.data[i]=rand()%10;
- List.len++;
- cout<<List.data[i]<<" "; }
- cout<<endl;
- cout<<"输入要添加的数据:";
- cin>>InsertData;
- cout<<"输入要添加的位置:";
- cin>>InsertLocation;
- insert(&List,InsertData,InsertLocation);
- for(i=0;i<List.len;i++)
- {
- cout<<List.data[i]<<" ";
- }
- /* 暂停一会,也可以使用system("pause") */
- getchar();
- getchar();
- cout<<endl;
- return 0;
- }
Microsoft Visual C++ 6.0 下运行成功。