数据结构——有序线性表的的插入与删除
2015-09-08 17:00
645 查看
有序线性表的插入与删除
#include<iostream> #include<stdlib.h> # define LIST_INIT_SIZE 100 # define LISTINCREMENT 10 # define ElemType int # define OVERFLOW -1 # define ERROR -1 using namespace std; typedef struct { ElemType *elem; int length; int listsize; }SqList; void InitList_Sq(SqList &L) { L.elem = (ElemType * )malloc(LIST_INIT_SIZE*sizeof(ElemType)); if(! L.elem) exit(OVERFLOW); L.length = 0; L.listsize = LIST_INIT_SIZE; } int ListInsert_Sq(SqList &L, int i, ElemType e) { if(i > L.length) { cout << "ERROR"; return ERROR; } if(L.length >= L.listsize) { ElemType *newbase; newbase = (ElemType *)realloc(L.elem,(L.listsize + LISTINCREMENT) * sizeof(ElemType)); if(!newbase) exit(OVERFLOW); L.elem = newbase; L.listsize += LISTINCREMENT; } if(L.length == 0) { L.elem[0] = e; L.length++; return 1; } else { ElemType *p, *q; int wh; for(wh = 0; wh < L.length; wh++) { if( L.elem[wh] > e) break; } q = &L.elem[wh]; for( p = &(L.elem[L.length-1]); p >= q; p--) *(p+1) = *p; *q = e; L.length++; } } int ListDelete_Sq(SqList &L, int W, ElemType E) { if(W < 1 || W > L.length) return ERROR; ElemType *p, *q; p = &(L.elem[W-1]); E = *p; q = L.elem + L.length - 1; for(; p < q; p++) *p = *(p + 1); L.length--; cout << E <<endl; return E; } int main () { SqList L; InitList_Sq(L); int e; int n; cout << "Please input n:" << endl; cin >> n; cout << "Please input elem:" << endl; for(int i = 0; i < n; i++) { cin >> e; ListInsert_Sq( L, i, e); } cout << "Output the SqList:" << endl; for(int i = 0; i < L.length; i++) cout << L.elem[i] << " "; cout << endl; //------------------insert--------------------// cout << "Input the elem that will be insert:" << endl; int T; cin >> T; ListInsert_Sq( L, n, T); cout << "Output the SqList after insert:" << endl; for(int i = 0; i < L.length; i++) cout << L.elem[i] << " ";; cout << endl; //-----------------delete--------------------// cout << "Input the elem that will be deleted:" << endl; int W; int E; cin >> W; cout << "The " << W <<"th element will be deleted !" << endl; E = ListDelete_Sq( L, W, E); cout << "In the SqList after delete (elem " << E << ")is:"<<endl; for(int i = 0; i < L.length; i++) cout << L.elem[i] << " "; cout << endl; free(L.elem); L.elem = NULL; }
相关文章推荐
- Lua教程(七):数据结构详解
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- C#数据结构揭秘一
- 数据结构之Treap详解
- JavaScript数据结构和算法之图和图算法
- Java数据结构及算法实例:冒泡排序 Bubble Sort
- Java数据结构及算法实例:插入排序 Insertion Sort
- Java数据结构及算法实例:考拉兹猜想 Collatz Conjecture
- java数据结构之java实现栈
- java数据结构之实现双向链表的示例
- Java数据结构及算法实例:选择排序 Selection Sort
- Java数据结构及算法实例:朴素字符匹配 Brute Force
- Java数据结构及算法实例:汉诺塔问题 Hanoi
- Java数据结构及算法实例:快速计算二进制数中1的个数(Fast Bit Counting)
- java线性表排序示例分享
- java数据结构和算法学习之汉诺塔示例
- Java数据结构及算法实例:三角数字
- Java数据结构之简单链表的定义与实现方法示例
- 数据结构之AVL树详解
- qqwry.dat的数据结构图文解释第1/2页