您的位置:首页 > 理论基础 > 数据结构算法

数据结构 顺序表

2015-04-15 13:51 162 查看
#include<iostream>

#include<stdlib.h>

using namespace std;

struct list

{

int *elem;

int length;

//int listsize;

};

void begin(list &L,int len)

{

L.elem = new int[len];

if (!L.elem)

{

exit(-1);

}

else

{

L.length = 0;

//L.listsize = len;

cout << "顺序表建立成功" << endl;

}

}

void get(list &L, int len)

{

int i = 0;

for (i = 0; i < len; i++)

cin>>*(L.elem + i);

}

//*********插入元素***********

void charu(list &L, int j, int e, int len)

{

L.length = len;

int *q,*p;

if (j < 1 || j > L.length+1)

{

cout << "您输入的插入位置不正确" << endl;

exit(-1);

}

else

{

q = & (L.elem[j- 1]);

for ( p =( L.elem+L.length - 1); p>= q; --p)

{

*(p + 1) = *p;

}

/*q = &(L.elem[i - 1]);

for (p = &(L.elem[L.length - 1]); p >= q; --p)

*(p + 1) = *p;*/

}

//*q = e;

(L.elem[j - 1]) = e;

++L.length;

cout << "插入的元素为:" << *(L.elem + j - 1) << endl;

}

//*********删除函数***********

void shancu(list &L,int j,int &e)

{

int *q, *p;

if (j < 1 || j > L.length + 1)

{

cout << "您输入的删除位置不正确" << endl;

exit(-1);

}

else

{

p = &(L.elem[j - 1]);

e = *p;

q = L.elem + L.length - 1;

for (++p; p <= q; ++p)

*(p - 1) = *p;

}--L.length;

}

//**********输出函数***********

void suchun(list &L)

{

for (int i = 0; i <L.length; i++)

{

cout << *(L.elem + i);

}

}

int main()

{

list st1;

int a,e;

cout<<"请输入表长"<<endl;

cin>>a;

begin(st1, a);

get(st1, a);

cout<<"请输入插入位置(第几个元素前)"<<endl;

int t,x;

cin>>t;

cout<<"请输入要插入的值"<<endl;

cin>>x;

charu(st1, t, x, a);

cout<<"输出插入后的顺序表"<<endl;

suchun(st1);

cout << endl;

cout<<"请输入删除位置(第几个元素前)"<<endl;

int y;

cin>>y;

shancu(st1, y,e);

cout<<"输出删除后的顺序表"<<endl;

suchun(st1);

cout<<endl;

system("pause");

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: