#include <iostream> using namespace std; typedef int DataType; struct SeqList { int MAXNUM; int n; DataType *element; }; typedef struct SeqList *PSeqList; PSeqList createEmptySeq(int m) { PSeqList palist = (PSeqList) malloc (sizeof (struct SeqList)); if(palist !=NULL) { palist->element = (DataType*) malloc (sizeof(DataType)*m); if(palist->element) { palist->MAXNUM = m; palist->n = 0; return palist; } else free(palist); } cout<<"Out of space"<<endl; return NULL; } int isNULLSeq(PSeqList palist) { return (palist->n == 0); } //寻找x的下标 int locateSeq(PSeqList palist,DataType x) { int q; for(q = 0; q<palist->n; q++) if(palist->element[q] == x) return q; return -1; } //在下标为p的元素之前插入x; int insertPreSeq(PSeqList palist, int p,DataType x) { int q; if(palist->n >= palist->MAXNUM) { cout<<"Over flow"<<endl; return 0; } if(p<0 || p>palist->n) cout<<"Not exist"<<endl; //元素后移 for(q = palist->n-1; q>=p; q--) palist->element[q+1] = palist->element[q]; palist->element[p] = x; palist->n = palist->n + 1; return 1; } int insertAftSeq(PSeqList palist, int p,DataType x) { int q; if(palist->n >= palist->MAXNUM) { cout<<"Over flow"<<endl; return 0; } if(p<0 || p>palist->n) cout<<"Not exist"<<endl; //直接插入 palist->element[p] = x; palist->n = palist->n + 1; return 1; } void showSeq(PSeqList palist) { for(int i=0;i<palist->n;i++) cout<<palist->element[i]<<" "; cout<<endl; } //删除下标为p的元素 int deleteSeq(PSeqList palist,int p) { int q; if(p<0 || p>palist->n-1) { cout<<"Not exist"<<endl; return 0; } for(q=p; q<palist->n-1;q++) palist->element[q] = palist->element[q+1]; palist->n = palist->n-1; return 1; } //删除所有值为x的元素 //*********** 注意一下这种处理方法 ************* void delect_x(PSeqList palist,DataType x) { int i,k =0; for(i=0; i<palist->n; i++) { if(palist->element[i]!=x) { palist->element[k] = palist->element[i]; k++; } } palist->n = k; } int main() { cout<<"创建队列"<<endl; int m; cin>>m; PSeqList palist = createEmptySeq(m); cout<<"输入元素"<<endl; int count=0; DataType data; //为什么用了while来输入元素后,后面的cin都跳过 while(cin>>data) { insertAftSeq(palist,count,data); count++; } cout<<"创建的顺序表为:"<<endl; showSeq(palist); //我也按照输入来更改顺序表,可是程序直接跳过了cin //如果是int data,insertAftSeq(palist,0,data)这样 //一个个写插入的元素的话就没问题。。。。。 cout<<"在下标为2的位置插入100"<<endl; insertPreSeq(palist,2,100); showSeq(palist); cout<<"删除第三个元素"<<endl; deleteSeq(palist,3); cout<<"删除元素:3"<<endl; delect_x(palist,3); showSeq(palist); return 0; }
原文:http://www.cnblogs.com/tianjintou/p/4521076.html