顺序表(完整可运行代码)
顺序表c语言的程序代码
//----------------------------线性表的动态分配顺序存储结构-------------------------# include "stdio.h"# include "malloc.h"# include "stdlib.h"# define M 5 //线性表存储空间的初始分配量# define N 2 //线性表存储空间的分配增量typedef struct {int *elem; //存储空间基址int length; //当前长度int listsize; //当前分配的存储容量(以sizeof(int)为单位)}SqList;int InitList(SqList *L) { // 构造一个空的线性表LL->elem=(int *)malloc(M*sizeof(int));if(!L->elem) // 存储分配失败exit(-2);L->length=0; // 空表长度为0L->listsize=M; // 初始存储容量return 1;}int IntPut(SqList *L) { //输入数据int i,e;printf ("请输入你要输入数据的个数:\n");scanf ("%d",&e);if (1>e||5<e) { //判断输入数据的个数是否合格,若不合格请重新输入do{printf ("你输入的数据有误!请重新输入:\n");scanf ("%d",&e);}while(1>e||5<e);}printf ("输入正确!\n请开始输入数据并用空格隔开:\n");for (i=0;i<e;i++) { //开始输入数据scanf ("%d",&L->elem[i]);L->length=L->length+1;}return 1;}int OutPut(SqList *L) { //输出数据int i;for (i=0;i<L->length;i++) {printf ("%d",L->elem[i]);printf ("\n");}return 1;}int Find(SqList *L) { //在顺序线性表L中查找第i个值,若找到,则打印出对应的值int i;printf ("请输入你要查找的数据序号:\n");scanf ("%d",&i);if (1>i||L->length<i) { //判断输入的序号是否合格,若不合格请重新输入do{printf ("你输入的数据有误!请重新输入:\n");scanf ("%d",&i);}while(1>i||L->length<i);}printf ("输入的序号正确!\n你输入的序号所对应的数据是:\n");printf ("%d\n",L->elem[i-1]); //打印出对应的值return 0;}int ListInsert(SqList *L) { // 在顺序线性表L的第i个元素之前插入新的元素e,// i的合法值为1≤i≤ListLength(L)+1 int *y,*q,*p,i,e;printf ("请输入你要插入的数据序号:\n");scanf ("%d",&i);if (1>i||(L->length+1)<i) { // 判断输入的序号是否合格,若不合格请重新输入do{printf ("你输入的数据有误!请重新输入:\n");scanf ("%d",&i);}while(1>i||(L->length+1)<i);}printf ("输入的序号正确!\n请输入你要插入的数据:\n");scanf ("%d",&e);if(L->length>=L->listsize) { // 当前存储空间已满,增加容量y=(int *)realloc(L->elem,(L->listsize+N)*sizeof(int));if(!y) // 存储分配失败exit(-2);L->elem=y; // 新基址L->listsize+=N; // 增加存储容量}q=&(L->elem[i-1]); // q为插入位置for(p=&(L->elem[L->length-1]);p>=q;--p) // 插入位置及之后的元素右移*(p+1)=*p;if(L->length>6){printf ("插入失败,线性表L已满!\n");return 1;}*q=e; // 插入e++L->length; // 表长增1return 1;}int ListDelete(SqList *L,int &e) { // 在顺序线性表L中删除第i个元素,并用e返回其值。
数据结构经典题目及c语言代码
数据结构经典题目及c语言代码一、线性表1. 顺序表顺序表是一种利用连续存储空间存储元素的线性表。
以下是一个顺序表的经典题目及C语言代码实现:```c#define MaxSize 50typedef struct {int data[MaxSize]; // 存储元素的数组int length; // 顺序表的当前长度} SeqList;// 初始化顺序表void initList(SeqList *L) {L->length = 0;}// 插入元素到指定位置void insert(SeqList *L, int pos, int elem) {if (pos < 1 || pos > L->length + 1) {printf("插入位置无效\n");return;}if (L->length == MaxSize) {printf("顺序表已满,无法插入\n"); return;}for (int i = L->length; i >= pos; i--) { L->data[i] = L->data[i - 1];}L->data[pos - 1] = elem;L->length++;}// 删除指定位置的元素void delete(SeqList *L, int pos) {if (pos < 1 || pos > L->length) {printf("删除位置无效\n");return;}for (int i = pos - 1; i < L->length - 1; i++) {L->data[i] = L->data[i + 1];}L->length--;}// 获取指定位置的元素值int getElement(SeqList *L, int pos) {if (pos < 1 || pos > L->length) {printf("位置无效\n");return -1;}return L->data[pos - 1];}```2. 链表链表是一种利用非连续存储空间存储元素的线性表。
数据结构实验报告-线性表(顺序表实现)
实验1:线性表(顺序表的实现)一、实验项目名称顺序表基本操作的实现二、实验目的掌握线性表的基本操作在顺序存储结构上的实现。
三、实验基本原理顺序表是由地址连续的的向量实现的,便于实现随机访问。
顺序表进行插入和删除运算时,平均需要移动表中大约一半的数据元素,容量难以扩充四、主要仪器设备及耗材Window 11、Dev-C++5.11五、实验步骤1.导入库和一些预定义:2.定义顺序表:3.初始化:4.插入元素:5.查询元素:6.删除元素:7.销毁顺序表:8.清空顺序表:9.顺序表长度:10.判空:11.定位满足大小关系的元素(默认小于):12.查询前驱:13.查询后继:14.输出顺序表15.归并顺序表16.写测试程序以及主函数对顺序表的每一个操作写一个测试函数,然后在主函数用while+switch-case的方式实现一个带菜单的简易测试程序,代码见“实验完整代码”。
实验完整代码:#include <bits/stdc++.h>using namespace std;#define error 0#define overflow -2#define initSize 100#define addSize 10#define compareTo <=typedef int ElemType;struct List{ElemType *elem;int len;int listsize;}L;void init(List &L){L.elem = (ElemType *) malloc(initSize * sizeof(ElemType)); if(!L.elem){cout << "分配内存失败!";exit(overflow);}L.len = 0;L.listsize = initSize;}void destroy(List &L){free(L.elem);L.len = L.listsize = 0;}void clear(List &L){L.len = 0;}bool empty(List L){if(L.len == 0) return true;else return false;}int length(List L){return L.len;}ElemType getElem(List L,int i){if(i < 1 || i > L.len + 1){cout << "下标越界!";exit(error);}return L.elem[i - 1];}bool compare(ElemType a,ElemType b) {return a compareTo b;}int locateElem(List L,ElemType e) {for(int i = 0;i < L.len;i++){if(compare(L.elem[i],e))return i;}return -1;}int check1(List L,ElemType e){int idx = -1;for(int i = 0;i < L.len;i++)if(L.elem[i] == e)idx = i;return idx;}bool check2(List L,ElemType e){int idx = -1;for(int i = L.len - 1;i >= 0;i--)if(L.elem[i] == e)idx = i;return idx;}int priorElem(List L,ElemType cur_e,ElemType pre_e[]) {int idx = check1(L,cur_e);if(idx == 0 || idx == -1){string str = "";str = idx == 0 ? "无前驱结点" : "不存在该元素";cout << str;exit(error);}int cnt = 0;for(int i = 1;i < L.len;i++){if(L.elem[i] == cur_e){pre_e[cnt ++] = L.elem[i - 1];}}return cnt;}int nextElem(List L,ElemType cur_e,ElemType next_e[]){int idx = check2(L,cur_e);if(idx == L.len - 1 || idx == - 1){string str = "";str = idx == -1 ? "不存在该元素" : "无后驱结点";cout << str;exit(error);}int cnt = 0;for(int i = 0;i < L.len - 1;i++){if(L.elem[i] == cur_e){next_e[cnt ++] = L.elem[i + 1];}}return cnt;}void insert(List &L,int i,ElemType e){if(i < 1 || i > L.len + 1){cout << "下标越界!";exit(error);}if(L.len >= L.listsize){ElemType *newbase = (ElemType *)realloc(L.elem,(L.listsize + addSize) * sizeof(ElemType));if(!newbase){cout << "内存分配失败!";exit(overflow);}L.elem = newbase;L.listsize += addSize;for(int j = L.len;j > i - 1;j--)L.elem[j] = L.elem[j - 1];L.elem[i - 1] = e;L.len ++;}void deleteList(List &L,int i,ElemType &e){if(i < 1 || i > L.len + 1){cout << "下标越界!";exit(error);}e = L.elem[i - 1];for(int j = i - 1;j < L.len;j++)L.elem[j] = L.elem[j + 1];L.len --;}void merge(List L,List L2,List &L3){L3.elem = (ElemType *)malloc((L.len + L2.len) * sizeof(ElemType)); L3.len = L.len + L2.len;L3.listsize = initSize;if(!L3.elem){cout << "内存分配异常";exit(overflow);}int i = 0,j = 0,k = 0;while(i < L.len && j < L2.len){if(L.elem[i] <= L2.elem[j])L3.elem[k ++] = L.elem[i ++];else L3.elem[k ++] = L2.elem[j ++];}while(i < L.len)L3.elem[k ++] = L.elem[i ++];while(j < L2.len)L3.elem[k ++] = L2.elem[j ++];}bool visit(List L){if(L.len == 0) return false;for(int i = 0;i < L.len;i++)cout << L.elem[i] << " ";cout << endl;return true;}void listTraverse(List L){if(!visit(L)) return;}void partion(List *L){int a[100000],b[100000],len3 = 0,len2 = 0; memset(a,0,sizeof a);memset(b,0,sizeof b);for(int i = 0;i < L->len;i++){if(L->elem[i] % 2 == 0)b[len2 ++] = L->elem[i];elsea[len3 ++] = L->elem[i];}for(int i = 0;i < len3;i++)L->elem[i] = a[i];for(int i = 0,j = len3;i < len2;i++,j++) L->elem[j] = b[i];cout << "输出顺序表:" << endl;for(int i = 0;i < L->len;i++)cout << L->elem[i] << " ";cout << endl;}//以下是测试函数------------------------------------void test1(List &list){init(list);cout << "初始化完成!" << endl;}void test2(List &list){if(list.listsize == 0)cout << "线性表不存在!" << endl;else{int len;ElemType num;cout << "选择插入的元素数量:" << endl;cin >> len;cout << "依次输入要插入的元素:" << endl;for(int i = 1;i <= len;i++){cin >> num;insert(list,i,num);}cout << "操作成功!" << endl;}}void test3(){if(L.listsize == 0)cout << "线性表不存在!" << endl;else{cout << "请输入要返回的元素的下标" << endl;int idx;cin >> idx;cout << "线性表中第" << idx << "个元素是:" << getElem(L,idx) << endl;}}void test4(){if(L.listsize == 0)cout << "线性表不存在!" << endl;else{int idx;ElemType num;cout << "请输入要删除的元素在线性表的位置" << endl;cin >> idx;deleteList(L,idx,num);cout << "操作成功!" << endl << "被删除的元素是:" << num << endl; }}void test5(){if(L.listsize == 0)cout << "线性表不存在!" << endl;else{destroy(L);cout << "线性表已被销毁" << endl;}}void test6(){if(L.listsize == 0)cout << "线性表不存在!" << endl;else{clear(L);cout << "线性表已被清空" << endl;}}void test7(){if(L.listsize == 0)cout << "线性表不存在!" << endl;else cout << "线性表的长度现在是:" << length(L) << endl;}void test8(){if(L.listsize == 0)cout << "线性表不存在!" << endl;else if(empty(L))cout << "线性表现在为空" << endl;else cout << "线性表现在非空" << endl;}void test9(){if(L.listsize == 0)cout << "线性表不存在!" << endl;else{ElemType num;cout << "请输入待判定的元素:" << endl;cin >> num;cout << "第一个与目标元素满足大小关系的元素的位置:" << locateElem(L,num) << endl;}}void test10(){if(L.listsize == 0)cout << "线性表不存在!" << endl;else{ElemType num,num2[initSize / 2];cout << "请输入参照元素:" << endl;cin >> num;int len = priorElem(L,num,num2);cout << num << "的前驱为:" << endl;for(int i = 0;i < len;i++)cout << num2[i] << " ";cout << endl;}}void test11(){if(L.listsize == 0)cout << "线性表不存在!" << endl;else{ElemType num,num2[initSize / 2];cout << "请输入参照元素:" << endl;cin >> num;int len = nextElem(L,num,num2);cout << num << "的后继为:" << endl;for(int i = 0;i < len;i++)cout << num2[i] << " ";cout << endl;}}void test12(List list){if(L.listsize == 0)cout << "线性表不存在!" << endl;else{cout << "输出线性表所有元素:" << endl;listTraverse(list);}}void test13(){if(L.listsize == 0)cout << "初始线性表不存在!" << endl; else{List L2,L3;cout << "初始化一个新线性表" << endl;test1(L2);test2(L2);cout << "归并两个线性表" << endl;merge(L,L2,L3);cout << "归并成功!" << endl;cout << "输出合并后的线性表" << endl;listTraverse(L3);}}void test14(){partion(&L);cout << "奇偶数分区成功!" << endl;}int main(){std::ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);int op = 0;while(op != 15){cout << "-----------------menu--------------------" << endl;cout << "--------------1:初始化------------------" << endl;cout << "--------------2:插入元素----------------" << endl;cout << "--------------3:查询元素----------------" << endl;cout << "--------------4:删除元素----------------" << endl;cout << "--------------5:销毁线性表--------------" << endl;cout << "--------------6:清空线性表--------------" << endl;cout << "--------------7:线性表长度--------------" << endl;cout << "--------------8:线性表是否为空----------" << endl;cout << "--------------9:定位满足大小关系的元素--" << endl;cout << "--------------10:查询前驱---------------" << endl;cout << "--------------11:查询后继---------------" << endl;cout << "--------------12:输出线性表-------------" << endl;cout << "--------------13:归并线性表-------------" << endl;cout << "--------------14:奇偶分区---------------" << endl;cout << "--------------15: 退出测试程序-----------" << endl;cout << "请输入指令编号:" << endl; if(!(cin >> op)){cin.clear();cin.ignore(INT_MAX,'\n');cout << "请输入整数!" << endl;continue;}switch(op){case 1:test1(L);break;case 2:test2(L);break;case 3:test3();break;case 4:test4();break;case 5:test5();break;case 6:test6();break;case 7:test7();break;case 8:test8();break;case 9:test9();break;case 10:test10();break;case 11:test11();break;case 12:test12(L);break;case 13:test13();break;case 14:test14();break;case 15:cout << "测试结束!" << endl;default:cout << "请输入正确的指令编号!" << endl;}}return 0;}六、实验数据及处理结果1.初始化:2.插入元素3.查询元素(返回的是数组下标,下标从0开始)4.删除元素(位置从1开始)5.销毁顺序表6.清空顺序表7.顺序表长度(销毁或清空操作前)8.判空(销毁或清空操作前)9.定位满足大小关系的元素(销毁或清空操作前)说明:这里默认找第一个小于目标元素的位置且下标从0开始,当前顺序表的数据为:1 4 2 510.前驱(销毁或清空操作前)11.后继(销毁或清空操作前)12.输出顺序表(销毁或清空操作前)13.归并顺序表(销毁或清空操作前)七、思考讨论题或体会或对改进实验的建议通过本次实验,我掌握了定义线性表的顺序存储类型,加深了对顺序存储结构的理解,进一步巩固和理解了顺序表的基本操作,如建立、查找、插入和删除等。
java顺序表的基本操作代码
Java顺序表的基本操作代码一、什么是顺序表顺序表(Sequential List)是一种常见的线性数据结构,它由一组按照顺序存储的元素组成,其中每个元素都有唯一的索引值。
顺序表中的元素在物理存储上是连续的。
在Java中,顺序表可以通过数组进行实现,也可以通过ArrayList类来实现。
本文将分别介绍这两种实现方式。
二、数组实现顺序表1. 创建顺序表int[] array = new int[capacity];int size = 0;上述代码创建了一个容量为capacity的整型数组array,同时将顺序表的大小初始化为0。
2. 插入元素在顺序表的末尾插入元素:public void addLast(int element) {if (size == array.length) {// 扩容操作int[] newArray = new int[array.length * 2];System.arraycopy(array, 0, newArray, 0, array.length);array = newArray;}array[size] = element;size++;}在指定位置插入元素:public void add(int index, int element) {if (index < 0 || index > size) {throw new IndexOutOfBoundsException();}if (size == array.length) {// 扩容操作int[] newArray = new int[array.length * 2];System.arraycopy(array, 0, newArray, 0, index);System.arraycopy(array, index, newArray, index + 1, size - index); array = newArray;} else {System.arraycopy(array, index, array, index + 1, size - index);}array[index] = element;size++;}3. 删除元素删除末尾元素:public void removeLast() {if (size == 0) {throw new NoSuchElementException();}size--;}删除指定位置的元素:public void remove(int index) {if (index < 0 || index >= size) {throw new IndexOutOfBoundsException();}System.arraycopy(array, index + 1, array, index, size - index - 1);size--;}4. 获取元素获取指定位置的元素:public int get(int index) {if (index < 0 || index >= size) {throw new IndexOutOfBoundsException();}return array[index];}修改指定位置的元素:public void set(int index, int element) {if (index < 0 || index >= size) {throw new IndexOutOfBoundsException();}array[index] = element;}5. 查询元素查找指定元素的索引:public int indexOf(int element) {for (int i = 0; i < size; i++) {if (array[i] == element) {return i;}}return -1;}判断顺序表是否为空:public boolean isEmpty() {return size == 0;}三、ArrayList实现顺序表ArrayList是Java提供的一个动态数组类,它实现了List接口,可以方便地进行顺序表的操作。
(完整版)数据结构线性表的主要程序代码
数据结构顺序表的主要代码(LIZHULIN)1./***有头结点的单链表的初始化、建立(表头插入、表尾插入)、求长度、插入、删除、输出***//***********单链表的初始化、建立、输出*****************/#include<stdio.h>#include<stdlib.h>typedef struct Lnode{ /*定义线性表的单链表存储结构*/int data;struct Lnode *next;}LinkList;/****************单链表的初始化*************************/Initlist(LinkList *L){ /*动态申请存储空间*/L = (LinkList *)malloc(sizeof(struct Lnode));/*建立头结点*/L->next = NULL;}/*************建立一个带头结点的单链表,在表尾插入***************/Create_L(LinkList *L,int n){LinkList *p,*q; int i;Initlist(L); /*单链表初始化*/q=L;printf("input the value\n");for(i = n;i>0;--i){p = (LinkList*)malloc(sizeof(struct Lnode));scanf("%d",&p->data); /*输入元素值*/q->next = p;p->next = NULL;q=p;/*插入到表尾*/}} /* Create_L *//*************建立一个带头结点的单链表,在表头插入**************Create_L(LinkList *L,int n){LinkList *p; int i;Initlist(L); /*单链表初始化/*需要注意第一个数据插入时的情况/*Insert the Firset nodep = (LinkList*)malloc(sizeof(struct Lnode));printf("input the value\n");scanf("%d",&p->data); /*输入元素值L->next = p;p->next = NULL;/*将第二个及后面的数据插入for(i = n-1;i>0;--i){p = (LinkList*)malloc(sizeof(struct Lnode));printf("input a value\n");scanf("%d",&p->data); /*输入元素值p->next = L->next;L->next = p;/*插入到表头}} /* Create_L *//*************************求单链表的长度***********************/int Length_LinkList(LinkList *L){LinkList *p;int i=0;p=L->next;while(p!=NULL){i++;p=p->next;}return i;}/*Length_LinkList*//*************************在第i个结点前插入数据x *********************/ Insert_LinkList(LinkList *L, int i, int x){LinkList *p,*s;int j=0;p=L;/*寻找第i个结点*/while(j<i-1 && p!=NULL){++j;p=p->next;}if (!p) return 0;/*如果表长小于i,则无意义*//*插入元素x */s=(LinkList *)malloc(sizeof(struct Lnode));s->data=x;s->next=p->next;p->next=s;}/*********************删除第i个元素,并用y将其值返回************************/ int Delete_LinkList(LinkList *L, int i){LinkList *p,*q;int y;int j=0;p=L;/*寻找第i个结点*/while(j<i-1 && p!=NULL){++j;p=p->next;}if (!p) return 0;/*如果表长小于i,则无意义*/q=p->next;y=q->data;p->next=q->next;free(q) ;return y;} /*Delete_LinkList*//*******************单链表值的输出****************/void display(LinkList *L) /*字母链表的输出*/{LinkList *p;p=L->next;while (p!=NULL){printf("%d ",p->data);p=p->next;}}/*************主程序**********************/ main(){LinkList *L;int len;int n=0;int x=15;int y;int i=4;L = (LinkList*)malloc(sizeof(struct Lnode));/*L->data = 0;*/L->next =NULL;printf("input the length of L ,n\n");scanf("%d",&n);printf("\n");Create_L(L,n);Insert_LinkList(L, i, x);/* y=Delete_LinkList(L,i);printf("the delete elment is y=%d\n",y);len=Length_LinkList(L);printf("the length of L is %d",len);*/display(L);getch();}2./***无头结点的单链表建立、插入、求长度、插入、删除、输出*****/#include<stdio.h>#include<stdlib.h>typedef struct Lnode{ /*定义线性表的单链表存储结构*/int data;struct Lnode *next;}LinkList;/*************Create ***************/Link_Creat(LinkList *L,int n){LinkList *q,*p;int i;printf("input the data\n");scanf("%d",&L->data);p=L;for(i=2; i<=n;i++){q=(LinkList *)malloc(sizeof(struct Lnode));scanf("%d",&q->data);p->next=q;q->next=NULL;p=q;}}/**************OutPut*********************/Link_Display(LinkList *L){LinkList *p;p=L;while(p!=NULL){printf("%d ",p->data);p=p->next;}}/***************Main()**************************/main(){LinkList *L;int n;L=(LinkList *)malloc(sizeof(struct Lnode));L->data=0;L->next=NULL;printf("Please input the length of LinkList, n\n");scanf("%d",&n);Link_Creat(L,n);Link_Display(L);getch();}3./*********顺序表的建立、查找、插入运算********/#include <stdio.h>#include <stdlib.h>typedef int datatype;#define list_maxsize 20/********* define for node struct ************/typedef struct{datatype data[list_maxsize];int length;}SqList;/********** InitList ************/void InitList(SqList *L){L->length = 0;}/*******Creat SqList********/void Create_SqList(SqList *L){int i=0;InitList(L);printf("input SqList.data\n");scanf("%d",&L->data[0]);while(L->data[i]!=-1){++i;scanf("%d",&(L->data[i]));}L->length = i;}/********* the length of SqList****************/int ListLength(SqList *L){return L->length;}/************ GetElem L->data[i]************/int GetElem(SqList *L, int i){if(i<1 || i>L->length){ printf("Position Error");return;}elsereturn L->data[i-1];}/**************** Output the SqList**************/ void Display_SqList(SqList *L){int i,n;n=ListLength(L);printf("the length is %d ",n);for(i=0;i<n;i++)printf("%d ", L->data[i]);}/****************Main()**************************/ main(){SqList *L;/*printf("input the length of SqList\n");scanf("%d",&len);*/Create_SqList(L);Display_SqList(L);getch();}4./*********顺序表的归并运算********/#include <stdio.h>#include <stdlib.h>typedef int datatype;#define list_maxsize 20/********* define for node struct ************/typedef struct{datatype data[list_maxsize];int length;}SqList;/********** InitList ************/void InitList(SqList *L){L->length = 0;}/************ Creat SqList*************/void Create_SqList(SqList *L){int i=0;InitList(L);printf("input the data of SqList\n");scanf("%d",&L->data[0]);while(L->data[i]!=-1){++i;scanf("%d",&(L->data[i]));}L->length = i;}/********* the length of SqList****************/int ListLength(SqList *L){return L->length;}/************ GetElem L->data[i]************/int GetElem(SqList *L, int i){if(i<1 || i>L->length){ printf("Getelem Position Error");return;}return L->data[i-1];}/************ Insert Operation *********/void ListInsert(SqList *L,int i, int x){SqList *q, *p;if(i<1 || i>L->length){printf("the insert position error");return ;}q = &(L->data[i-1]); /*q为插入位置*/for(p=&(L->data[L->length-1]); p>=q; --p)*(p+1) = *p;L->data[i-1] = x;++L->length;}/********* LA and LB Merged LC ***************/ void MergeList(SqList *LA,SqList *LB,SqList *LC) {int La_len,Lb_len,ai,bj;int i,j;int k;i=j=1;InitList(LC);La_len = ListLength(LA);Lb_len = ListLength(LB);LC->length = La_len+Lb_len;/*for(k=0;k<LC->length;k++)LC->data[k] = 0; */k=0;while((i<=La_len)&&(j<=Lb_len)){ai= GetElem(LA, i);bj= GetElem(LB, j);if(ai<bj){++k;ListInsert(LC,k,ai);++i;}elseif(ai==bj){++k;ListInsert(LC,k,ai);++k;ListInsert(LC,k,bj);++i;++j;}else{++k;ListInsert(LC,k,bj);++j;}}while(i<=La_len){/*Append the residual node into LA */ai= GetElem(LA, i);++i;++k;ListInsert(LC,k,ai);}while(j<=Lb_len){/*Append the residual node into LA */bj= GetElem(LB, j);++j;++k;ListInsert(LC,k,bj);}LC->length = La_len+Lb_len;}/**************** Output the SqList**************/ void Display_SqList(SqList *L){int i,n;n=ListLength(L);printf("the length is %d ",n);for(i=0;i<n;i++)printf("%d ", L->data[i]);}/****************Main()**************************/ main(){SqList *LA , *LB, *LC;Create_SqList(LA);Create_SqList(LB);MergeList(LA,LB,LC);Display_SqList(LC);getch();}5./**** 用带头结点的循环单链表解决约瑟夫问题***********/#include<stdio.h>#include<stdlib.h>typedef struct Lnode{ /*定义线性表的单链表存储结构*/int data;struct Lnode *next;}LinkList;/****************单链表的初始化*************************/Initlist(LinkList *L){ /*动态申请存储空间*/L = (LinkList *)malloc(sizeof(struct Lnode));/*建立头结点*/L->next = L;}/*************建立一个带头结点的循环单链表,数据值为1,2,3,...n,在表尾插入***************/Create_L(LinkList *L,int n){LinkList *p; int i;Initlist(L); /*单链表初始化p=L;for(i = n;i>0;--i){q = (LinkList*)malloc(sizeof(struct Lnode));q->data = i; /*输入元素值p->next =qq->next = L;/*插入到表尾}} /* Create_L *//*******************单链表值的输出****************/void display(LinkList *L) /*字母链表的输出*/{LinkList *p;p=L->next;while (p->next!=L){printf("%d ",p->data);p=p->next;}}/*************主程序**********************/ main(){LinkList *L;int n;L = (LinkList*)malloc(sizeof(struct Lnode));/*L->data = 0;*/L->next =L;printf("input the length of L ,n\n");scanf("%d",&n);printf("\n");Create_L(L,n);display(L);getch();}6./******** 无头结点的循环单链表的建立**************/#include<stdio.h>#include<stdlib.h>typedef struct Lnode{ /*定义线性表的单链表存储结构*/int data;struct Lnode *next;}LinkList;/*************Create ***************/Link_Creat(LinkList *L,int n){LinkList *q,*p;int i;printf("input the data\n");scanf("%d",&L->data);p=L;for(i=2; i<=n;i++){q=(LinkList *)malloc(sizeof(struct Lnode));scanf("%d",&q->data);p->next=q;q->next=NULL;p=q;}p->next = L;/*尾结点指向第一个结点*/}/**************OutPut*********************/Link_Display(LinkList *L){LinkList *p;p=L;printf("%d ",p->data);p=p->next;while(p->next !=L){printf("%d ",p->data);p=p->next;}}/***************Main()**************************/ main(){LinkList *L;int n;L=(LinkList *)malloc(sizeof(struct Lnode));L->data=0;L->next=NULL;printf("Please input the length of LinkList, n\n");scanf("%d",&n);Link_Creat(L,n);Link_Display(L);getch();}。
java顺序表的基本操作代码
java顺序表的基本操作代码Java顺序表是一种基于数组实现的线性结构,具有随机访问、元素插入和删除等基本操作。
在Java中,我们可以通过定义一个数组来创建一个顺序表,并通过编写一些基本操作代码来实现对该顺序表的操作。
一、顺序表的定义和初始化在Java中,我们可以通过定义一个数组来创建一个顺序表。
下面是一个简单的代码示例:```public class SeqList<T> {private Object[] elementData; // 存储元素的数组private int size; // 当前元素个数// 构造函数public SeqList(int capacity) {elementData = new Object[capacity];size = 0;}}```在上述代码中,我们定义了一个SeqList类,其中包含了存储元素的数组elementData和当前元素个数size两个成员变量。
构造函数SeqList(int capacity)用于创建指定长度为capacity的数组,并将当前元素个数初始化为0。
二、顺序表的插入操作1. 在指定位置插入元素在Java中,我们可以通过下标来访问数组中的元素。
因此,在进行插入操作时,需要先将要插入位置之后的所有元素向后移动一位,然后再将新元素插入到指定位置上。
下面是一个简单的代码示例:```// 在指定位置插入元素public void insert(int index, T element) {if (index < 0 || index > size) {throw new IndexOutOfBoundsException("插入位置越界"); }// 判断数组是否已满,若已满则扩容if (size == elementData.length) {ensureCapacity(size * 2);}// 将要插入位置之后的所有元素向后移动一位for (int i = size - 1; i >= index; i--) {elementData[i + 1] = elementData[i];}// 插入新元素elementData[index] = element;size++;}// 扩容方法private void ensureCapacity(int minCapacity) {if (minCapacity > elementData.length) {Object[] newArray = new Object[minCapacity];System.arraycopy(elementData, 0, newArray, 0, size);elementData = newArray;}}```在上述代码中,我们首先判断要插入的位置是否越界。
顺序表的基本操作-完整代码和拆开分析
顺序表的基本操作-完整代码和拆开分析1 #include<stdio.h> //增+删+改+初始化+输出2 #include<stdlib.h>3#define MaxSize 10 此数决定了后⾯插⼊数据的多少,超过该数字输出顺序表的时候不是正确的数4 typedef int ElementType;5struct SqList {6 ElementType elem[MaxSize];7int Length;8 };910 typedef struct SqList *PtrNode;11 typedef PtrNode List;1213 List InitList();14int InSert(List L, int i, ElementType x) ;15int Delete(List L, int i);16int GetElem(List L, int i);17int Print(List L);1819int main() {20int a;21 ElementType x;22 List list;23 list=InitList();24 InSert(list, 1, 1);25 InSert(list, 2, 2);26 InSert(list, 3, 3);27 Print(list);28 printf("第⼀处的元素为:%d\n",GetElem(list,1));29 printf("要删除第⼏处的数据");30 scanf("%d", &a);31 Delete(list, a);32 Print(list);33 }34 List InitList() { //初始化35 List L;36 L = (List)malloc(sizeof(struct SqList));37 L->Length = 0;38 printf("初始化成功\n");39return L;40 }41//插⼊42int InSert(List L, int i, ElementType x) {43int j;44if (i<1 || i>L->Length + 1) {45 printf("越界"); return0;46 }47for (j = L->Length; j >= i; j--) {48 L->elem[j] = L->elem[j-1]; L—>elem[j+1]=L->elem[j];是错误的,j是数组长度,⽤作数组索引时要⼩⼼,所以上⾯的条件不应该是j>i49 }50 L->elem[i - 1] = x; //第i处,因为是数组所以减⼀51 L->Length++;52return1;53 }54//删除55int Delete(List L, int i) {56int j;57if (i<1 || i>L->Length) {58 printf("越界"); return0;59 }60for (j = i - 1; j < L->Length-1; j++)61 L->elem[j] = L->elem[j+1];62 L->Length--;63return1;6465 }66//查找第i处的数据67int GetElem(List L, int i) {68if (i<1 || i>L->Length) {69 printf("越界"); return0;70 }71return L->elem[i - 1];72 }73//遍历输出74int Print(List L) {75int i = 0;76for (i; i < L->Length; i++)77 printf("%d\n", L->elem[i]);78 }1. 初始化:1 List InitList() { //初始化2 List L;3 L = (List)malloc(sizeof(struct SqList));4 L->Length = 0;5 printf("初始化成功\n");6return L;7 }(1)malloc开辟空间,L指向该空间(2)空间的Length属性赋值为零;2.插⼊:int InSert(List L, int i, ElementType x) {43int j;44if (i<1 || i>L->Length + 1) {45 printf("越界"); return0;46 }47for (j = L->Length; j > i; j--) {48 L->elem[j + 1] = L->elem[j];49 }此处错误,修改见上⾯完整代码50 L->elem[i - 1] = x; //第i处,因为是数组所以减⼀51 L->Length++;52return1;53 }(1)判断输⼊的待插⼊位置是否合理------要插⼊的位置是否⼩于1,或者⼤于顺序表的长度Length+1【与其他的不同:可以在Length+1位置插⼊】(2)如果不满⾜(1),则循环赋值------从顺序表最后⼀个位置开始,从后向前依次将前⼀个位置的值赋给后⼀个位置(3)插⼊待插⼊数x-------将x赋值给待插⼊位置(4)顺序表长度加⼀3.删除:int Delete(List L, int i) {56int j;57if (i<1 || i>L->Length) {58 printf("越界"); return0;59 }60for (j = i - 1; j < L->Length-1; j++)61 L->elem[j] = L->elem[j+1];62 L->Length--;63return1;6465 }(1)判断输⼊的待插⼊位置是否合理------要插⼊的位置是否⼩于1,或者超出顺序表的长度Length(2)如果不满⾜(1),则循环赋值-------从待删除位置开始,从前向后依次将后⼀个位置的值赋值给前⼀个位置(3)顺序表长度减⼀4.查找:67int GetElem(List L, int i) {68if (i<1 || i>L->Length) {69 printf("越界"); return0;70 }71return L->elem[i - 1];72 }(1)判断输⼊的待插⼊位置是否合理------要插⼊的位置是否⼩于1,或者超出顺序表的长度Length(2)直接根据数组下标返回该值5.输出:74int Print(List L) {75int i = 0;76for (i; i < L->Length; i++)77 printf("%d\n", L->elem[i]);78 }根据数组下标直接循环输出**********************************************Tips:初始化和查找必须有返回值(初始化要将创建的顺序表名返回;查找要将找到的值返回),其他函数可以不设返回值或者返回1。
C语言顺序表的实现代码
C语⾔顺序表的实现代码本⽂实例为⼤家分享了C语⾔实现顺序表的具体代码,供⼤家参考,具体内容如下seqlist.h#ifndef __SEQLIST_H__#define __SEQLIST_H__#include<cstdio>#include<malloc.h>#include<assert.h>#define SEQLIST_INIT_SIZE 8#define INC_SIZE 3 //空间增量的⼤⼩typedef int ElemType;typedef struct Seqlist {ElemType *base;int capacity; //顺序表容量int size; //表的⼤⼩}Seqlist;bool Inc(Seqlist *list);//增加顺序表的容量void InitSeqlist(Seqlist *list); //初始化顺序表void push_back(Seqlist *list, ElemType x); //在顺序表的末尾插⼊元素void push_front(Seqlist *list, ElemType x); //在顺序表的头部插⼊元素void show_list(Seqlist *list); //显⽰顺序表中的元素void pop_back(Seqlist *list); //删除顺序表最后⼀个元素void pop_front(Seqlist *list); //删除顺序表第⼀个元素void insert_pos(Seqlist *list, int pos, ElemType x);//在顺序表的选定位置上插⼊数据int find(Seqlist *list, ElemType key); //在顺序表中查找元素key的下标int length(Seqlist *list);//求顺序表的长度void delete_pos(Seqlist *list, int pos); //删除顺序表中特定位置的数据元素void delete_val(Seqlist *list, int key);//删除顺序表中值为key的数据元素void sort(Seqlist *list);//冒泡排序void reverse(Seqlist *list);//逆置顺序列表void clear(Seqlist *list);//清除顺序表中的所有元素void destroy(Seqlist *list);//摧毁顺序表void merge(Seqlist *lt, Seqlist *la, Seqlist *lb);//合并两个顺序列表#endif //__SEQLIST_H__seqlist.cpp#include"seqlist.h"bool Inc(Seqlist *list) {ElemType *newbase = (ElemType*)realloc(list, sizeof(ElemType)*(list->capacity + INC_SIZE)); //重新分配内存空间if (newbase == NULL) {printf("内存空间已满,⽆法再分配内存空间!\n");return false;}list->base = newbase;list->capacity += INC_SIZE;return true;}void InitSeqlist(Seqlist *list) {list->base = (ElemType*)malloc(sizeof(ElemType)*SEQLIST_INIT_SIZE);assert(list->base != NULL);list->capacity = SEQLIST_INIT_SIZE;list->size = 0;}void push_back(Seqlist *list, ElemType x) {if (list->size >= list->capacity && !Inc(list)) { //Inc(list)⽤来判断增加顺序表容量是否成功,只有在失败的情况下才会进⼊if语句中 printf("顺序表容量已满,⽆法再在表尾继续插⼊新元素!\n");return;}list->base[list->size] = x;list->size++;}void push_front(Seqlist *list, ElemType x) {if (list->size >= list->capacity && !Inc(list)) {printf("顺序表容量已满,⽆法再在表头插⼊新元素!\n"); return;}for (int i = list->size;i > 0;i--) {list->base[i] = list->base[i - 1];}list->base[0] = x;list->size++;}void show_list(Seqlist *list) {for (int i = 0;i < list->size;i++) {printf("%d ", list->base[i]);}printf("\n");}void pop_back(Seqlist *list) {if (list->size == 0) {printf("顺序表已空,⽆法再在表尾删除元素!\n");return;}list->size--;}void pop_front(Seqlist *list) {if (list->size == 0) {printf("顺序表已空,⽆法再在表头删除元素!\n");return;}for (int i = 0;i < list->size - 1;i++) {list->base[i] = list->base[i + 1];}list->size--;}void insert_pos(Seqlist *list, int pos, ElemType x) {if (pos<0 || pos>list->size) {printf("插⼊位置不合法,⽆法插⼊元素!\n");return;}if (list->size >= list->capacity && !Inc(list)) {printf("顺序表容量已满,⽆法在插⼊新的元素!\n");return;}for (int i = list->size;i > pos;i--) {list->base[i] = list->base[i - 1];}list->base[pos] = x;list->size++;}int find(Seqlist *list, ElemType key) {for (int i = 0;i < list->size;i++) {if (list->base[i] == key)return i;}return -1;}int length(Seqlist *list) {return list->size;}void delete_pos(Seqlist *list, int pos) {if (pos < 0 || pos >= list->size) {printf("删除位置不合法,⽆法删除元素!\n");return;}for (int i = pos;i < list->size - 1;i++) {list->base[i] = list->base[i + 1];}list->size--;}void delete_val(Seqlist *list, int key) {int pos = find(list, key);if (pos == -1) {printf("顺序表中没有这个元素!\n");return;}delete_pos(list, pos);}void sort(Seqlist *list) {for (int i = 0;i < list->size - 1;i++) {//排序的趟数(例如5个数据需要⽐较4趟)for (int j = 0;j < list->size - 1 - i;j++) {//每⼀趟⽐较中的⽐较次数(例如5个数据在第0趟需要⽐较4次) if (list->base[j] > list->base[j + 1]) {ElemType temp = list->base[j];list->base[j] = list->base[j + 1];list->base[j + 1] = temp;}}}}void reverse(Seqlist *list) {if (list->size == 0 || list->size == 1) return;int low = 0, high = list->size - 1;while (low < high) {ElemType temp = list->base[low];list->base[low] = list->base[high];list->base[high] = temp;low++;high--;}}void clear(Seqlist *list) {list->size = 0;}void destroy(Seqlist *list) {free(list->base);list->base = NULL;list->capacity = 0;list->size = 0;}void merge(Seqlist *lt, Seqlist *la, Seqlist *lb) {lt->capacity = la->size + lb->size;lt->base = (ElemType*)malloc(sizeof(ElemType)*lt->capacity);assert(lt->base != NULL);int ia = 0, ib = 0, ic = 0;while (ia < la->size&&ib < lb->size) {if (la->base[ia] < lb->base[ib]) {lt->base[ic++] = la->base[ia++];}else {lt->base[ic++] = lb->base[ib++];}}while (ia < la->size) {lt->base[ic++] = la->base[ia++];}while (ib < lb->size) {lt->base[ic++] = lb->base[ib++];}lt->size = la->size + lb->size;show_list(lt);}main.cpp#include"seqlist.h"void main() {Seqlist list;InitSeqlist(&list);ElemType item;int select = 1;while (select) {printf("*******************************************\n");printf("*[1] push_back [2] push_front *\n");printf("*[3] show_list [4] pop_back *\n");printf("*[5] pop_front [6] insert_pos *\n");printf("*[7] find [8] length *\n");printf("*[9] delete_pos [10] delete_value *\n");printf("*[11] sort [12] reverse *\n");printf("*[13] clear [14] merge *\n");printf("*[0] quit_system *\n");printf("*******************************************\n");printf("请选择:>>");scanf("%d", &select);if (select == 0) break;switch (select) {case 1:printf("请输⼊要插⼊的数据(-1结束):>");while (scanf("%d", &item), item != -1) {//先输⼊item的值,只要item不等于-1就接着循环 push_back(&list, item);}break;case 2:printf("请输⼊要插⼊的数据(-1结束):>");while (scanf("%d", &item), item != -1) {push_front(&list, item);}break;case 3:show_list(&list);break;case 4:pop_back(&list);break;case 5:pop_front(&list);break;case 6:printf("请输⼊要插⼊的数据:>");scanf("%d", &item);printf("请输⼊要插⼊的位置:>");scanf("%d", &pos);insert_pos(&list, pos, item);break;case 7:printf("请输⼊要查找的数据:>");scanf("%d", &item);pos = find(&list, item);if (pos == -1)printf("查找的数据元素不在顺序表中!\n");elseprintf("查找的数据元素在顺序表中的下标位置为%d\n", pos);break;case 8:printf("顺序表的长度为%d\n", length(&list));break;case 9:printf("请输⼊要删除数据在顺序表中的下标位置:>");scanf("%d", &pos);delete_pos(&list, pos);break;case 10:printf("请输⼊要删除数据的值:>");scanf("%d", &item);delete_val(&list, item);break;case 11:sort(&list);break;case 12:reverse(&list);break;case 13:clear(&list);break;Seqlist mylist, yourlist;ElemType item1, item2;InitSeqlist(&mylist);InitSeqlist(&yourlist);printf("请输⼊顺序表1中的元素值(-1结束):>");while (scanf("%d", &item1), item1 != -1) {push_back(&mylist, item1);}printf("请输⼊顺序表2中的元素值(-1结束):>");while (scanf("%d", &item2), item2 != -1) {push_back(&yourlist, item2);}merge(&list, &mylist, &yourlist);destroy(&mylist);destroy(&yourlist);break;default:printf("输⼊的选择错误!请重新输⼊!\n");break;}}destroy(&list);}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
实验一 顺序表的操作代码
#include<stdio.h>#define LIST_INIT_SIZE 100#define LISTINCREMENT 10typedef struct{int *elem;int length;int listsize;}sqlist;void InitList_sq(sqlist *L,int i){ int m;L->elem=(int *)malloc(LIST_INIT_SIZE*sizeof(int));if(!L->elem)printf("顺序表创建失败\n");L->length=i;L->listsize=LIST_INIT_SIZE;for(m=0;m<i;m++){printf("请输入第%d个元素的值\n",m+1);scanf("%d",&L->elem[m]);}printf("顺序表创建成功\n");}void DestoryList_sq(sqlist *L){if(&L){free(L);L=NULL;printf("顺序表已销毁\n");}else printf("顺序表销毁失败\n");}void ListEmpty_sq(sqlist *L){if(L->length!=0)printf("顺序表不为空\n");elseprintf("顺序表为空\n");}void ListLength_sq(sqlist *L){printf("顺序表的长度为%d\n",L->length);}void ListInsert_sq(sqlist *L,int j,int k){int *p;if(j<1||j>L->length+1)return 0;if(L->length>=L->listsize){int *newbase=(int *)realloc(L->elem,(L->listsize+LISTINCREMENT)*sizeof(int));if(!newbase)return 0;L->elem=newbase;L->listsize+=LISTINCREMENT;}int *q=&(L->elem[j-1]);for(p=&(L->elem[L->length-1]);p>=q;--p)*(p+1)=*p;*q=k;++L->length;printf("插入成功\n");return 0;}void ListDelete_sq(sqlist *L,int j){int *p,*q;if(j<1||j>L->length)printf("您输入的i值有误\n");p=&(L->elem[j-1]);q=L->elem+L->length-1;for(++p;p<=q;++p)*(p-1)=*p;--L->length;printf("顺序表该位置已成功删除\n");}void LocateElem_sq(sqlist *L,int j){int i;if(!L->length)printf("查询失败,顺序表为空!\n");elsefor(i=0;i<L->length;i++){if(L->elem[i]==j)printf("查询成功,该元素的下标为%d\n",i);return 0;}printf("查询失败,该元素不在顺序表中\n");}void ClearList_sq(sqlist *L){if(!L)printf("顺序表未创建\n");else{L->length=0;printf("顺序表清空成功\n");}}void GetElem_sq(sqlist *L,int j){if(!L)printf("顺序表未创建\n");else if(j<0||j>L->length-1){printf("您输入的数字有误。
顺序表源代码
#include<iostream>usingnamespace std;constint MaxSize = 10;template<class T>class SeqList{public:SeqList(){ length = 0; } //无参构造函数SeqList(T a[], int n); //有参构造函数int Insert(int i, T x); //在线性表中第i个位置插入值为x的元素int Delete(int i); //删除线性表的第i个元素int Locate(T x); //按值查找,求线性表中值为x的元素序号void PrintList(); //遍历线性表,按序号依次输出各元素private:T data[MaxSize]; //存放数据元素的数组int length; //线性表的长度};template<class T>SeqList<T>::SeqList(T a[], int n){if (n>MaxSize) throw"参数非法";for (int i = 0; i<n; i++)data[i] = a[i];length = n;}template<class T>int SeqList<T>::Insert(int i, T x){if (length >= MaxSize){/*throw "上溢";*/return 0;}if (i<1 ) return 0;if (i>length + 1) return 0;for (int j = length; j >= i; j--)data[j] = data[j - 1]; //注意第j个元素存在数组下标为j-1处data[i - 1] = x;length++;return 1;}template<class T>int SeqList<T>::Delete(int i){int x;if (length == 0) { /*throw "下溢"; */return -1; }if (i<1 || i>length) { /*throw "位置"; */return -1; }x = data[i - 1];for (int j = i; j<length; j++)data[j - 1] = data[j]; //注意此处j已经是元素所在的数组下标length--;return x;}template<class T>int SeqList<T>::Locate(T x){for (int i = 0; i<length; i++)if (data[i] == x) return i + 1; //下标为i的元素等于x,返回其序号i+1return 0; //退出循环,说明查找失败}template<class T>void SeqList<T>::PrintList(){for (int d2(0); d2 < length; d2++)cout<< data[d2] <<endl;}int menu(){int menu_input;system("cls");cout<<"1.插入元素"<<endl;cout<<"2.删除元素"<<endl;cout<<"3.查找元素"<<endl;cout<<"4.显示所有元素"<<endl;//okcout<<"5.结束程序运行"<<endl;//okcout<<"请输入1-5:";cin>>menu_input;return menu_input;}//主程序int main(){int main_a,main_b[MaxSize];cout<<"请输入线性表长度(最长长度为10):";cin>>main_a;if (main_a<= 0 || 10 <main_a) { cout<<"超出长度\n"; system("pause"); return 0; } cout<<"请输入线性表数值\n";for (int i = 0; i<main_a ; i++){cin>>main_b[i];}SeqList<int>main_xxb(main_b,main_a);//初始化完毕cout<<"初始化完毕\n";system("pause");int main_g1,main_g2;//main_g为过渡值int main_input;do{main_input = menu();switch (main_input) {case 1:{cout<<"输入插入数值";cin>> main_g1;cout<<"插入位置";cin>> main_g2;main_g1 = main_xxb.Insert(main_g2, main_g1);if (main_g1 == 0)cout<<"插入失败";elsecout<<"插入成功";system("pause");break;}case 2:{cout<<"删除元素位置";cin>> main_g1;main_g2 = main_xxb.Delete(main_g1);if (main_g2 == -1)cout<<"删除失败";elsecout<<"删除成功";system("pause");break;}case 3:{cin>> main_g1;main_g2=main_xxb.Locate(main_g1);if (main_g2 == 0)cout<<"没有查找到"<<endl;elsecout<<"该数值位于线性表的第"<< main_g2<<endl;system("pause");break;}case 4:main_xxb.PrintList(); system("pause"); break;case 5: main_input = 0; break;default: cout<<"选择错误。
顺序表的实现-包含插入-删除-查找等操作-完整源代码-有注释-包你喜欢.
实验一顺序表的实现实验目的:熟练掌握顺序表的基本操作(插入、删除、查找等)实验内容:顺序表中的基本操作的实现(初始化、插入、删除、求表长、按值查找、按位置查找)实验要求:以顺序表的动态分配存储结构来实现;所有基本操作均应该以函数的形式表示;要有运行结果并考虑到顺序表中所有情况。
一、实验算法描述:1、顺序表的声明和创建typedef struct{int* data;//int*型元素int length;//顺序表的实际长度int listsize;//顺序表的最大长度}sqlist;void creatsqlist(sqlist &list){list.data=(int*)malloc(sizeof(int)*maxsize);//开辟一个名为l的顺序表if(!list.data)//判断顺序表是否存在exit(1);list.length=0;list.listsize=maxsize;}2、初始化函数initsqlist(list)void initsqlist(sqlist &list)//初始化操作{int* p;int n;cout<<"请输入顺序表元素数(1-50):"<<endl;//让用户输入顺序表元素个数cin>>n;cout<<"您申请的顺序表的长度是---"<<n<<endl;p=list.data;//p指向头指针cout<<"请依次输入无重复数字的有序顺序表(相邻数据用空格隔开,回车键完成输入):"<<endl;for(int i=0;i<n;i++)//逐个赋值{cin>>*p;p++;list.length++;}cout<<"您输入的递增顺序表为:"<<endl;//打印出初始化的顺序表for(i=0;i<n;i++)cout<<list.data[i]<<"\t";cout<<endl;}3、输出函数put(list)void put(sqlist &list) //输出函数{ int i;for(i=0;i<list.length;i++)cout<<list.data[i]<<"\t";cout<<endl;}4、定位函数locateElem(list)void locateElem(sqlist &list){int i,j=0,b;cout<<"请输如要查找的字符:\n";cin>>b;for(i=0;i<list.length;i++)if(list.data[i]==b){j=i+1;break;}if(j)cout<<"该数字的位置是:"<<j<<endl;elsecout<<"很抱歉,表中没有这个数字,请重试!"<<endl; }5、插入函数insert(list)void insert(sqlist &list)//插入函数{int i;cout<<"您想在第几位插入数字:\n";cin>>i;int x;cout<<"请输入要插入的数字:\n";cin>>x;int j;if(i<0||i>list.length){cout<<"位置错误"<<endl;put(list);}else{ for(j=list.length;j>=i;j--)list.data[j]=list.data[j-1];list.data[j]=x;list.length++;}cout<<"插入操作完成后的顺序表:"<<endl;put(list);}6、删除函数delete1(list)和delete2(list)void delete1(sqlist &list)//删除第i个位置的数字的函数{int i,b;cout<<"请输入你想要删除数据的位置:"<<endl;cin>>i;if(i<0||i>list.length){cout<<"输入错误!"<<endl;return;}else{b=list.data[i-1];for(i=i-1;i<list.length-1;i++)list.data[i]=list.data[i+1];--list.length;cout<<"需要删除的元素是:"<<b<<endl;cout<<"删除操作完成后的顺序表是:"<<endl;put(list);}}void delete2(sqlist &list)//删除指定数字的函数{int b;cout<<"输入您想删除的数字:"<<endl;cin>>b;int i,j=0;for(i=0;i<list.length;i++){if(list.data[i]==b){j=i+1;break;}}if(j!=0){for(;i<list.length-2 ;i++)list.data[i]=list.data[i+1];--list.length;cout<<"该位置是第"<<i<<"位"<<endl;cout<<"删除操作完成后的顺序表是:"<<endl;put(list);}elsecout<<"很遗憾,表中没有找到此数字,删除不成功,请重试!"<<endl;}二、实验程序描述:主函数如下:int main(){int flag;sqlist l;creatsqlist(l);initsqlist(l);cout<<endl<<"********************************************************* *****************"<<endl;cout<<"请输入要进行的操作序号:\n";cout<<"1.插入字符"<<endl<<"2.查找数字"<<endl<<"3.删除第i位数字"<<endl<<"4.删除指定数字"<<endl<<"0.退出"<<endl<<endl;cin>>flag;do{switch(flag){case 1:insert(l);break;case 2:locateElem(l);break;case 3:delete1(l);break;case 4:delete2(l);break;default:cout<<"请重新输入||代码错误"<<endl;}cout<<"*********************************************************** ***************"<<endl;cout<<"请输入要进行的操作序号:\n";cout<<"1.插入字符"<<endl<<"2.查找数字"<<endl<<"3.删除第i位数字"<<endl<<"4.删除指定数字"<<endl<<"0.退出"<<endl<<endl;cin>>flag;}while(flag!=0);return 0;}三、实验结果(输入和输出):1、输入界面:2、插入操作:3、查找操作:4、删除操作:最新文件仅供参考已改成word文本。
C语言实现顺序表的基本操作(从键盘输入生成线性表,读txt文件生成线性表和数组生成线性表-。。。
C语⾔实现顺序表的基本操作(从键盘输⼊⽣成线性表,读txt⽂件⽣成线性表和数组⽣成线性表-。
经过三天的时间终于把顺序表的操作实现搞定了。
(主要是在测试部分停留了太长时间)1. 线性表顺序存储的概念:指的是在内存中⽤⼀段地址连续的存储单元依次存储线性表中的元素。
2. 采⽤的实现⽅式:⼀段地址连续的存储单元可以⽤固定数组或者动态存储结构来实现,这⾥采⽤动态分配存储结构。
3. 顺序表结构体⽰意图三种写法完整代码:第⼀种写法. 从键盘输⼊⽣成线性表--完整代码如下,取值操作实际上就是删除操作的部分实现,这⾥就不写了#include<stdio.h>#include<stdlib.h>#include<malloc.h>#define LIST_INIT_SIZE 100#define LISTINCREMENT 10#define OK 1#define ERROR 0#define INFEASIBLE -1#define OVERFLOW -2#define TRUE 1#define FALSE 0typedef int Status;typedef int ElemType;typedef struct SqList{ElemType *elem;int length;int listsize;}SqList;Status InitList(SqList &L){L.elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType));if (!L.elem){printf("ERROR\n");return ERROR;}L.length = 0;L.listsize = LIST_INIT_SIZE;return OK;}Status ListEmpty(SqList L) //判空{if (L.length = 0) return TRUE;else return FALSE;}Status ListInsert(SqList &L, int i, ElemType e) //插⼊{ElemType *p, *q;ElemType *newbase;int j;if (i < 1 || i > L.length + 1) return ERROR;if (L.length >= L.listsize){newbase = (ElemType *)realloc(L.elem, (L.listsize + LISTINCREMENT) * sizeof(ElemType));if (newbase == NULL){printf("realloc failed!\n");return ERROR;//exit(-1);}L.elem = newbase;L.listsize += LISTINCREMENT;}p = L.elem+i-1;for( q = L.elem + L.length - 1; q>= p; --q ){*(q+1) = *q;}*p = e;++L.length;return OK;}Status CrtList(SqList &L) // 从键盘输⼊数据⽣成线性表{printf("输⼊整数,以0结束:\n");ElemType e;int i = 1;scanf("%d", &e);while (e != 0){if (!ListInsert(L, i, e)) return ERROR;i++;scanf("%d", &e);}return OK;}Status CrtList2(SqList &L, ElemType d[], int n) // 从数组⽣成线性表{int i;for (i = 0; i < n; ++i){if (!ListInsert(L, i + 1, d[i])) return ERROR;}return OK;}Status ListDelet(SqList &L, int i, ElemType &e) //删除{if ((i<1) || (i>L.length)) return ERROR;ElemType *p, *q;p = &(L.elem[i - 1]);e = *p;q = L.elem + L.length - 1;for (++p; p <= q; ++p) *(p - 1) = *(p);--L.length;return OK;}Status GetElem(SqList &L, int i, ElemType &e) //取值{if ((i <= 0) || (i>L.length)) return ERROR;else{e = L.elem[i - 1];return OK;}}Status compare(ElemType a, ElemType b) //⽐较{if (a == b) return TRUE;else return FALSE;}int LocateElem(SqList L, ElemType e) //定位{Status compare(ElemType a, ElemType b);int i;for (i = 0; i<L.length; i++){if (compare(L.elem[i], e))return ++i;}if (i == L.length) return0;}Status PriorElem(SqList L, ElemType cur_e, ElemType &pre_e) //求直接前驱{int LocateElem(SqList L, ElemType e);int i = LocateElem(L, cur_e);if ((i == 0) || (i == 1)) return ERROR;pre_e = L.elem[i - 2];return OK;}int ListLength(SqList L) //求长度{int length = L.length;return length;}void MergeList(SqList La, SqList Lb, SqList &Lc) //归并{Lc.length = La.length + Lb.length;Lc.listsize = Lc.length;Lc.elem = (ElemType*)malloc(Lc.length*sizeof(ElemType));if (Lc.elem == NULL) exit(OVERFLOW);int i, j, k;for (i = 0, j = 0, k = 0; (i<La.length) && (j<Lb.length); k++){if (La.elem[i]<Lb.elem[j]){Lc.elem[k] = La.elem[i];i++;}else{Lc.elem[k] = La.elem[j];j++;}}while (i<La.length){Lc.elem[k] = La.elem[i];i++;k++;}while (j<Lb.length){Lc.elem[k] = Lb.elem[j];j++;k++;}}void vist(ElemType e){printf("%d ", e);}Status ListTraverse(SqList L) //遍历{int i;if (L.length == 0) printf("⽆元素");for (i = 0; i<L.length; i++){vist(L.elem[i]);}if (i == L.length){printf("\n");return OK;}else return ERROR;}Status ListClear(SqList L) //清空{if (L.elem == NULL) return ERROR;int i;for (i = 0; i<L.length; i++) L.elem[i] = 0;L.length = 0;return OK;}Status DestroyList(SqList &L) //销毁{if (L.elem == NULL) return ERROR;free(L.elem);L.length = 0;L.listsize = 0;return OK;}void PrnList(SqList L) //打印{int i;for (i = 0; i < L.length; ++i){printf("%5d", L.elem[i]);}printf("\n");}int main(){int j, l;ElemType e, e1;SqList La;if (InitList(La)) printf("OK\n");else exit(INFEASIBLE);CrtList(La);PrnList(La);int k;printf("1:判空\n2:插⼊\n3:删除\n4:定位\n5:求长度\n6:直接前驱\n");printf("7:归并\n8:遍历\n9:清空\n10:销毁\n\n0:退出\n");scanf("%d", &k);while (k != 0){switch (k){case1:if (ListEmpty(La)) printf("empty\n");else printf("non-empty\n");break;case2:printf("在第⼏个位置插⼊何数:");scanf("%d%d", &j, &e);if (ListInsert(La, j, e)) printf("OK\n");else printf("ERROR\n");break;case3:printf("删除第⼏个数:");scanf("%d", &j);if (ListDelet(La, j, e))PrnList(La);printf("删除数为:%d\n", e);break;case4:printf("定位数字:");scanf("%d", &e);if (LocateElem(La, e) != 0) printf("OK,位序为:%d\n", LocateElem(La, e));else printf("ERROR\n");break;case5:l = ListLength(La);printf("ListLength=%d\n", l);break;case6:printf("寻找何数直接前驱:");scanf("%d", &e);if (PriorElem(La, e, e1)) printf("前驱为:%d\n", e1);else printf("ERROR\n");break;case7:SqList Lb, Lc;if (InitList(Lb)) printf("OK\n");else printf("ERROR\n");CrtList(Lb);MergeList(La, Lb, Lc);printf("有序归并后:\n");PrnList(Lc);break;case8:if (ListTraverse(La)) printf("遍历成功\n");else printf("遍历失败\n");break;case9:if (ListClear(La)) printf("清空成功\n");else printf("清空失败\n");break;case10:if (DestroyList(La)) printf("销毁完成\n");else printf("销毁失败\n");return0;default:printf("ERROR\n");}scanf("%d", &k);}return0;}View Code第⼆种写法. 从txt⽂件读⼊⽣成线性表--完整代码如下:#include<stdio.h>#include<stdlib.h>#define OK 1#define ERROR 0#define OVERFLOW -1#define TRUE 1#define FALSE 0#define INIT_LIST_SIZE 100#define LISTINCREMENT 10typedef int Status;typedef int ElemType;typedef struct{ElemType *elem;int length;int listsize;}SqList;Status InitList(SqList *L){L->elem = (ElemType*)malloc(INIT_LIST_SIZE*sizeof(ElemType));if (!L->elem) exit(OVERFLOW);L->length = 0;L->listsize = INIT_LIST_SIZE;return OK;}Status ListEmpty(SqList L) //判空{if (L.length = 0) return TRUE;else return FALSE;}Status ListInsert(SqList *L, int i, ElemType e) //插⼊{ElemType *newbase, *q, *p;if (i<1 || i>L->length + 1) return ERROR;if (L->length>L->listsize){newbase = (ElemType*)realloc(L->elem, (L->listsize + LISTINCREMENT)*sizeof(ElemType));if (!newbase) exit(OVERFLOW);L->elem = newbase;L->listsize += LISTINCREMENT;}q = L->elem + i - 1; //q为插⼊位置for (p = L->elem + L->length - 1; p >= q; p--){*(p + 1) = *p;}*q = e;++L->length;return OK;}Status ListDelete(SqList *L, int i, ElemType * e) //删除{ElemType * p, *q;if (i<1 || i>L->length) return ERROR;p = L->elem + i - 1; //p为被删除元素位置*e = *p; //被删除元素的值赋值给eq = L->elem + L->length - 1; //表尾元素位置for (++p; p <= q; ++p){*(p - 1) = *p;}L->length--;return OK;}Status GetElem(SqList *L, int i, ElemType * e) //取值{if (i<1 || i>L->length) return ERROR;*e = *(L->elem + i - 1); //获取第i个元素的地址return OK;}int LocateElem(SqList L, ElemType e) //定位{int i;for (i = 0; i<L.length; i++){if (L.elem[i]==e)return ++i;}if (i == L.length) return0;}Status PriorElem(SqList L, ElemType e, ElemType &pre_e) //求直接前驱{int LocateElem(SqList L, ElemType e);int i = LocateElem(L, e);if ((i == 0) || (i == 1)) return ERROR;pre_e = L.elem[i - 2];return OK;}Status GetLength(SqList *L) //求长度{return L->length;}void PrnList(SqList *L) //遍历{int i;for (i = 0; i<(*L).length; i++){if (i == 0)printf("(");printf(" %d ", L->elem[i]);if (i == (*L).length - 1)printf(")\n");}}Status ClearList(SqList *L) //清空{L->length = 0;return OK;}Status Destroy(SqList *L) //销毁{free(L->elem);L->elem = NULL;L->length = 0;L->listsize = 0;return OK;}int main(){int n = 0, rc;int a, i;int e, e1;SqList L;if (InitList(&L)) printf("OK\n");FILE *fp = fopen("D:/1.txt", "r");if (fp == NULL){printf("打开⽂件失败");}printf("从1.txt⽂件读⼊⼏个数:");scanf("%d", &n);for (i = 0; i< n; i++){fscanf(fp, "%d", &a);ListInsert(&L, i+1, a);}fclose(fp);PrnList(&L);char k;printf("\n1.插⼊\n2.删除\n3.取值\n4.定位\n5.直接前驱\n6.求长度\n7.遍历\n8.清空\n9.销毁\n"); while (1){k = getchar();switch (k){case'1':printf("在第⼏个位置插⼊何数:");scanf("%d%d", &i, &e);if (ListInsert(&L, i, e))printf("i=%d,e=%d 已经插⼊\n", i, e);else printf("插⼊失败\n");break;case'2':printf("删除第⼏个数:\n");scanf("%d", &i);if (ListDelete(&L, i, &e))printf("i=%d,e=%d 已经删除\n", i, e);else printf("删除失败\n");break;case'3':printf("取第⼏个数:\n");scanf("%d", &i);if (GetElem(&L, i, &e))printf("第i=%d号,e=%d 被取出!\n", i, e);else printf("取值失败\n");break;case'4':printf("定位数字:");scanf("%d", &e);if (LocateElem(L, e) != 0) printf("OK,位序为:%d\n", LocateElem(L, e));else printf("ERROR\n");break;case'5':printf("寻找何数直接前驱:");scanf("%d", &e);if (PriorElem(L, e, e1)) printf("前驱为:%d\n", e1);else printf("ERROR\n");break;case'6':printf("表长为%d\n", GetLength(&L));break;case'7':printf("遍历:\n");PrnList(&L);break;case'8':if (ClearList(&L)) printf("清空成功\n");else printf("清空失败\n");break;case'9':printf("销毁\n");Destroy(&L);printf("销毁成功\n");exit(0);return0;}}return0;}View Code第三种写法:读数组⽣成线性表--完整代码如下:#include<stdlib.h>#define OK 1#define ERROR 0#define OVERFLOW -1#define TRUE 1#define FALSE 0#define INIT_LIST_SIZE 100#define LISTINCREMENT 10typedef int Status;typedef int ElemType;typedef struct{ElemType *elem;int length;int listsize;}Sqlist;Status InitList(Sqlist *L){L->elem = (ElemType *)malloc(INIT_LIST_SIZE *sizeof(ElemType));if (!L->elem)exit(OVERFLOW);L->length = 0;L->listsize = INIT_LIST_SIZE;return OK;}Status ListEmpty(Sqlist L){if (L.length = 0)return ERROR;else return FALSE;}Status ListInsert(Sqlist *L, int i, ElemType e){ElemType *newbase, *p, *q;if (i<1 || i>L->length + 1)return ERROR;if (L->length > L->listsize){newbase = (ElemType *)realloc(L, (L->listsize + LISTINCREMENT)*sizeof(ElemType));if (!newbase)exit(OVERFLOW);L->elem = newbase;L->listsize += LISTINCREMENT;}p = L->elem + i - 1;for (q = L->elem + L->length - 1; q >= p; q--){*(q + 1) = *q;}*p = e;L->length++;return OK;}Status CreateList(Sqlist *L, ElemType element[], int n) // 从数组⽣成线性表{int i;for (i = 0; i < n; ++i){if (!ListInsert(L, i + 1, element[i])) return ERROR;}return OK;}Status ListDelete(Sqlist *L, int i, ElemType *e){ElemType *p, *q;if (i<1 || i>L->length)return ERROR;p = L->elem + i - 1;q = L->elem + L->length - 1;*e = *p;for (p++; q >= p; p++){*(p - 1) = *p;}L->length--;return OK;}Status GetElem(Sqlist *L, int i, ElemType *e){if (i<1 || i>L->length)return ERROR;return OK;}int LocateElem(Sqlist L, ElemType e){int i;for (i = 0; i < L.length; i++)if (L.elem[i] == e)return i + 1;}Status PriorElem(Sqlist L, ElemType e, ElemType &pr_e){int LocateElem(Sqlist L, ElemType e);int i = LocateElem(L, e);if (i<1 || i>L.length)return ERROR;pr_e = L.elem[i - 2];return OK;}Status GetLength(Sqlist *L){return L->length;}void PrnList(Sqlist *L){int i;for (i = 0; i < L->length; i++)printf("%d ", L->elem[i]);printf("\n");}Status ClearList(Sqlist *L){L->length = 0;return OK;}Status Destroy(Sqlist *L){free(L->elem);L->elem = NULL;L->length = 0;L->listsize = 0;return OK;}int main(){int i;int a, n = 0;int e, e1;Sqlist L;ElemType element[] = { 15, 3, 59, 27, 8, 11, 32 };if (InitList(&L))printf("OK\n");CreateList(&L, element, 7);PrnList(&L);char k;printf("\n1.插⼊\n2.删除\n3.取值\n4.定位\n5.直接前驱\n6.求长度\n7.遍历\n8.清空\n9.销毁\n"); while (1){k = getchar();switch (k){case'1':printf("在第⼏个位置插⼊何数:");scanf("%d%d", &i, &e);if (ListInsert(&L, i, e))printf("i=%d e=%d已经插⼊\n", i, e);break;case'2':printf("删除第⼏个数:");scanf("%d", &i);if (ListDelete(&L, i, &e))printf("i=%d e=%d已经删除\n", i, e);break;case'3':printf("取第⼏个数:");scanf("%d", &i);if (GetElem(&L, i, &e))printf("第i=%d e=%d已经取出\n", i, e);break;case'4':printf("定位何数:");scanf("%d", &e);if (LocateElem(L, e))printf("位序为:%d\n", LocateElem(L, e));break;case'5':printf("寻找何数的直接前驱:");scanf("%d", &e);if (PriorElem(L, e, e1))printf("前驱为:%d\n", e1);break;case'6':printf("表长为:%d\n", GetLength(&L));break;case'7':printf("遍历:\n");PrnList(&L);break;case'8':if (ClearList(&L))printf("清空成功!\n");break;case'9':if (Destroy(&L))printf("销毁成功!\n");exit(0);return0;}}return0;}View Code看懂了左⼿给你个栗⼦,给我关注点赞;看不懂右⼿给你个锤⼦,砸开脑壳看看有没有带脑⼦。
顺序表c语言代码
顺序表c语言代码顺序表是一种常见的数据结构,在C语言中可以使用数组来实现。
下面是一个简单的顺序表C语言代码示例:```c#include <stdio.h>#define MAXSIZE 100 // 定义最大容量typedef struct {int data[MAXSIZE]; // 数据存储数组int length; // 当前长度} SqList; // 顺序表类型定义// 初始化顺序表void InitList(SqList *L) {L->length = 0;}// 判断是否为空int ListEmpty(SqList L) {return L.length == 0;}// 获取元素int GetElem(SqList L, int i, int *e) {if (i < 1 || i > L.length) {return 0;}*e = L.data[i - 1];return 1;}// 插入元素int ListInsert(SqList *L, int i, int e) {if (L->length == MAXSIZE) { // 判断是否已满return 0;}if (i < 1 || i > L->length + 1) { // 判断插入位置是否合法return 0;}for (int j = L->length; j >= i; j--) { // 后移元素L->data[j] = L->data[j - 1];}L->data[i - 1] = e; // 插入新元素L->length++; // 长度加1return 1;}// 删除元素int ListDelete(SqList *L, int i, int *e) {if (i < 1 || i > L->length) { // 判断删除位置是否合法 return 0;}*e = L->data[i - 1]; // 取出需要删除的元素for (int j = i; j < L->length; j++) { // 前移元素L->data[j - 1] = L->data[j];}L->length--; // 长度减1return 1;}// 打印顺序表void PrintList(SqList L) {for (int i = 0; i < L.length; i++) {printf('%d ', L.data[i]);}printf('');}int main() {SqList L;InitList(&L);ListInsert(&L, 1, 1);ListInsert(&L, 2, 2);ListInsert(&L, 3, 3);ListInsert(&L, 4, 4);PrintList(L);int e;ListDelete(&L, 2, &e);printf('Delete element: %d', e);PrintList(L);return 0;}```在这个例子中,我们使用了结构体来定义了一个顺序表类型,其中包括数据存储数组和当前长度。
数据结构源代码(全)
/*顺序表的操作#include<iostream>#include<stdlib.h>using namespace std;Release 13.12 rev 9501 (2013/12/25 19:25:45) gcc 4.7.1 Windows/unicode - 32 bit #define MAX_SIZE 100typedef struct{int *emel;int lenth;}Sq;void init(Sq &l);void create(Sq &l);void trval(Sq &l);void find_value(Sq &l);void find_position(Sq &l);void insert(Sq &l);void dele(Sq &l);int main(){Sq l;init(l);create(l);trval(l);find_value(l);find_position(l);insert(l);trval(l);dele(l);trval(l);return 0;}void init(Sq &l){l.emel =new int[MAX_SIZE];if(l.emel ==NULL){cout<<"\t申请空间失败!"<<endl;exit(1);}l.lenth=0;cout<<"\t成功申请空间!该顺序表的长度目前为:"<<l.lenth<<endl; }void create(Sq &l){cout<<"\t请输入你想输入元素的个数:";int x;cin>>x;if((x<1)&&(x>MAX_SIZE)){cout<<"\t你说输入的数不在范围里"<<endl;return;}int i;for(i=0;i<x;i++){cin>>l.emel[i];}l.lenth=x;cout<<"\t成功赋值!"<<endl;}void trval(Sq &l){int i;cout<<"l(";for(i=0;i<l.lenth;i++){cout<<l.emel[i]<<" ";}cout<<")"<<" 该顺序表现在的长度为:"<<l.lenth<<endl;}void find_value(Sq &l){int x,t=0;cout<<"\t请输入你要查找的值:";cin>>x;int i;for(i=0;i<l.lenth;i++){if(l.emel[i]==x){t=1;cout<<"\t成功找到该元素,它是顺序表的第"<<i+1<<"个元素!"<<endl;}}if(t==0){cout<<"\t无该元素!"<<endl;}}void find_position(Sq &l){int x;cout<<"\t请输入你要查找的位置:";cin>>x;int i;if((x<1)||(x>l.lenth)){cout<<"\t输入的值不在范围内!"<<endl;return;}for(i=1;i<=l.lenth;i++){if(i==x){cout<<"\t成功找到该元素,该值是"<<l.emel[i-1]<<endl;}}}void insert(Sq &l){int i,x,y;cout<<"\t请输入你要插入的位置";cin>>x;cout<<"\t请输入你要插入的值";cin>>y;if((x<1)||(x>l.lenth)){cout<<"\t输入的值不在范围内!"<<endl;return;}if(x==l.lenth){l.emel[l.lenth]=y;l.lenth=l.lenth+1;return;}for(i=l.lenth;i>=x;i--){l.emel[i]=l.emel[i-1];}l.emel[x-1]=y;l.lenth=l.lenth+1;}void dele(Sq &l){int i,x;cout<<"\t请输入你要删除位置:";cin>>x;if((x<1)||(x>l.lenth)){cout<<"\t输入的值不在范围内!"<<endl;return;}for(i=x-1;i<=l.lenth;i++){l.emel[i]=l.emel[i+1];}l.lenth=l.lenth-1;}成功申请空间!该顺序表的长度目前为:0请输入你想输入元素的个数:3852成功赋值!l(8 5 2 ) 该顺序表现在的长度为:3请输入你要查找的值:5成功找到该元素,它是顺序表的第2个元素!请输入你要查找的位置:3成功找到该元素,该值是2请输入你要插入的位置3请输入你要插入的值10l(8 5 2 10 ) 该顺序表现在的长度为:4请输入你要删除位置:3l(8 5 10 ) 该顺序表现在的长度为:3--------------------------------Process exited with return value 0Press any key to continue . . .*//*#include<stdio.h>#include<stdlib.h>typedef struct Link{int num;struct Link *next;}L;L* creat(L* head){head=(L *)malloc(sizeof(L));if(head==NULL){printf("头节点申请失败!\n");exit(-1);}head->next=NULL;return head;}void insert(L* head){int x,i;printf("请输入你想输入数据的个数:");scanf("%d",&x);L *p,*q;p=head;for(i=0;i<x;i++){q=(L *)malloc(sizeof(L));if(q==NULL){printf("新点申请失败!\n");exit(-1);}printf("请输入值:");scanf("%d",&q->num);q->next=NULL;p->next=q;p=q;}}void print(L* head){L *p;p=head->next;while(p!=NULL){printf("值为:%d\n",p->num);p=p->next;}}int main(){L *head;head=creat(head);printf("成功创建头节点!!!\n");insert(head);printf("成功输入数据!!!\n");print(head);return 0;}*//*线性表的操作#include<stdio.h>#include<stdlib.h>typedef struct Link{int num;struct Link *next;}L;L* creat(L* head){head=(L *)malloc(sizeof(L));if(head==NULL){printf("头节点申请失败!\n");exit(-1);}head->next=NULL;return head;}void init(L* head){int x,i;printf("请输入你想输入数据的个数:");scanf("%d",&x);L *p,*q;p=head;for(i=0;i<x;i++){q=(L *)malloc(sizeof(L));if(q==NULL){printf("新点申请失败!\n");exit(-1);}printf("请输入值:");scanf("%d",&q->num);q->next=p->next;p->next=q;}}int print(L* head){L *p;int lenth=0;p=head->next;printf("\t\tL(");while(p!=NULL){lenth++;printf("%d ",p->num);p=p->next;}printf(")\n");return lenth;}int insert(L *head,int lenth){printf("\t\t请输入你要插入的元素的位置:");int in;scanf("%d",&in);if(in<1 || in>lenth){printf("\t\t输入值不在范围内!");return -1;}L *p,*q;p=head->next;q=(L *)malloc(sizeof(L));if(q==NULL){printf("新点申请失败!\n");return -1;}printf("\t\t请为新节点输入值:");scanf("%d",&q->num);int i=0;while(p!=NULL){i++;if(i==in-1){q->next=p->next;p->next=q;}p=p->next;}lenth++;return lenth;}int dele(L *head,int lenth){printf("\t\t请输入你要删除的元素的位置:");int out;scanf("%d",&out);if(out<1 || out>lenth){printf("\t\t输入值不在范围内!");return -1;}L *p,*q;p=head->next;q=head;int i=0;while(p!=NULL){i++;if(i==out){q->next=p->next;}q=p;p=p->next;}lenth--;return lenth;}void find(L *head,int lenth){printf("\t\t请输入你要查找的元素的位置:");int finder;scanf("%d",&finder);if(finder<1 || finder>lenth){printf("\t\t输入值不在范围内!");return ;}L *p;p=head->next;int i=0;while(p!=NULL){i++;if(i==finder){printf("\t\t你要找的该位置所对应的值为:%d\n",p->num);}p=p->next;}}int main(){L *head;head=creat(head);printf("成功创建头节点!!!\n");init(head);printf("成功输入数据!!!\n");int len;len=print(head);printf("\t\t该线性表的长度为:%d\n",len);len=insert(head,len);len=print(head);printf("\t\t插入后线性表的长度为:%d\n",len);len=dele(head,len);len=print(head);printf("\t\t删除后该线性表的长度为:%d\n",len);find(head,len);return 0;}*//*顺序表的合并#include<iostream>using namespace std;struct LA{int *pa;int lenth;};struct LB{int *pb;int lenth;};struct LC{int *pc;int lenth;};void mergelist(LA la,LB lb,LC &lc);int main(){int x,y;LA la;LB lb;cout<<"\t\t请给线性表LA和LB指定长度:";cin>>x>>y;la.pa =new int(sizeof(int)*x);lb.pb =new int(sizeof(int)*y);int i;for(i=0;i<x;i++){cout<<"请输入表LA的值:";cin>>la.pa[i];}cout<<endl;la.lenth=x;for(i=0;i<y;i++){cout<<"请输入表LB的值:";cin>>lb.pb[i];}lb.lenth=y;cout<<"LA(";for(i=0;i<x;i++){cout<<la.pa[i]<<" ";}cout<<")"<<endl;cout<<"LB(";for(i=0;i<y;i++){cout<<lb.pb[i]<<" ";}cout<<")"<<endl;LC lc;mergelist(la,lb,lc);return 0;}void mergelist(LA la,LB lb,LC &lc){lc.lenth=la.lenth+lb.lenth;lc.pc=new int(sizeof(int)*lc.lenth);int *pa=la.pa,*pb=lb.pb,*pc=lc.pc;int *pa_last=la.pa+la.lenth-1;int *pb_last=lb.pb+lb.lenth-1;while(pa<=pa_last && pb<=pb_last){if(*pa <= *pb){*pc++=*pa++;}else{*pc++=*pb++;}}while(pa<=pa_last){*pc++=*pa++;}while(pb<=pb_last){*pc++=*pb++;}cout<<"LC(";int i=0;for(i=0;i<lc.lenth;i++){cout<<lc.pc[i]<<" ";}cout<<")"<<endl;}*///栈/*#include<iostream>using namespace std;#include<stdlib.h>#define MAXSIZE 100typedef struct{int *base;int *top;int stacksize;}Sqstack;int Initstack(Sqstack &s);void Push(Sqstack &s,int e);void StackTraverse(Sqstack &s);void Gettop(Sqstack &s);void Pop(Sqstack &s);int main(){Sqstack s;Initstack(s);cout<<"\t\t初始化栈成功!"<<endl;Push(s,2);cout<<"\t\t2入栈成功!"<<endl;Push(s,4);cout<<"\t\t4入栈成功!"<<endl;Push(s,6);cout<<"\t\t6入栈成功!"<<endl;Push(s,8);cout<<"\t\t8入栈成功!"<<endl;cout<<"\n由栈底至栈顶的元素为:";StackTraverse(s);Gettop(s);Pop(s);Gettop(s);return 0;}int Initstack(Sqstack &s){s.base=new int[MAXSIZE];if(s.base==NULL){exit(1);}s.top=s.base;s.stacksize=MAXSIZE;}void Push(Sqstack &s,int e){if(s.top-s.base==s.stacksize){exit(1);}*s.top++=e;}void StackTraverse(Sqstack &s){int *p=s.base,i=0;while(p<s.top){i++;cout<<*p++<<" ";}cout<<"\t\t栈的长度是"<<i<<endl;}void Gettop(Sqstack &s){if(s.base==s.top){exit(1);}cout<<"栈顶元素是:"<<*(s.top-1)<<endl; }void Pop(Sqstack &s){if(s.top==s.base){exit(1);}cout<<"出栈的第一个元素是:";cout<<*--s.top<<" "<<endl;}*///队列例题:/*#include<iostream>#include<stdlib.h>using namespace std;#define MAXQSIZE 100typedef struct{int *base;int front;int rear;}SqQueue;int InitQueue(SqQueue &q);int EnQueue(SqQueue &q,int x);int DeQueue(SqQueue &q);int main(){SqQueue q;InitQueue(q);EnQueue(q,1);EnQueue(q,3);EnQueue(q,5);EnQueue(q,7);DeQueue(q);DeQueue(q);DeQueue(q);DeQueue(q);return 0;}int InitQueue(SqQueue &q){q.base=new int[MAXQSIZE];if(q.base==NULL){exit(1);}q.front=0;q.rear=0;return 0;}int EnQueue(SqQueue &q,int x){if((q.rear+1)%MAXQSIZE==q.front){exit(0);}q.base[q.rear]=x;q.rear=(q.rear+1)%MAXQSIZE;return 0;}int DeQueue(SqQueue &q){if(q.front==q.rear){exit(0);}int x=q.base[q.front];q.front=(q.front+1)%MAXQSIZE;cout<<x<<endl;}*//*#include<iostream>#include<stdlib.h>using namespace std;typedef struct Qnode{int date;struct Qnode *next;}Qnode,*Queueptr;typedef struct{Queueptr front; //队头指针Queueptr rear; //队尾指针}LinkQueue;int InitQueue(LinkQueue &Q);void EnQueue(LinkQueue &Q,int e);void TrvalQueue(LinkQueue Q);void DeQueue(LinkQueue &Q);int main(){LinkQueue Q;InitQueue(Q);EnQueue(Q,1);cout<<"\t元素1入队成功!"<<endl;EnQueue(Q,3);cout<<"\t元素3入队成功!"<<endl;EnQueue(Q,5);cout<<"\t元素5入队成功!"<<endl;EnQueue(Q,7);cout<<"\t元素7入队成功!"<<endl;cout<<"\t队列的元素分别是:"<<endl;TrvalQueue(Q);cout<<"\t第一个出队的元素是:"<<endl;DeQueue(Q);cout<<"\n\t第一个元素出队完成之后队列中从队头至队尾的元素为:";TrvalQueue(Q);return 0;}int InitQueue(LinkQueue &Q){Q.rear=new Qnode;Q.front=Q.rear;if(Q.front==NULL){exit(0);}Q.front->next=NULL;return 0;}void EnQueue(LinkQueue &Q,int e){Qnode *p=new Qnode;if(!p){exit(1);}p->date=e;p->next=NULL;Q.rear->next=p; //连接Q.rear=p; //修改队尾指针}void TrvalQueue(LinkQueue Q){Qnode *p=Q.front->next;//队头元素while(Q.front!=Q.rear){cout <<p->date<<" ";Q.front=p;p=p->next;}cout<<endl;}void DeQueue(LinkQueue &Q){if(Q.front==Q.rear){return;}Qnode *p=Q.front->next;cout<<"\t"<<p->date<<endl;Q.front->next=p->next;if(Q.rear==p){Q.rear=Q.front;delete p;}}*//*//表达式求值#include<iostream>#include<stdlib.h>#include<stdio.h>using namespace std;#define MAXSIZE 100typedef struct{char *base;char *top;char num;}OPND; //数据栈typedef struct{char *base;char *top;char c;}OPTR; //符号栈int Initstack(OPND &op_n,OPTR &op_t);void Pushstack(OPND &op_n,char ch);void Pushstack(OPTR &op_t,char ch);char Popstack(OPND &op_n,char ch);char Popstack(OPTR &op_t,char ch);char Gettop(OPTR op_t);char Gettop(OPND op_n);int In(char ch);char Precede(char x,char y);char operate(char z,char x,char y);int main(){OPND op_n;OPTR op_t;Initstack(op_n,op_t);Pushstack(op_t,'#');char ch;char p;cin>>ch;while(ch!='#' || Gettop(op_t)!='#'){if(!In(ch)){Pushstack(op_n,ch);cin>>ch;}else{switch( Precede(Gettop(op_t),ch) ){case '<':Pushstack(op_t,ch);cin>>ch;break;case '>':char x,y,z;x=Popstack(op_t,x);y=Popstack(op_n,y);z=Popstack(op_n,z);Pushstack(op_n,operate(z,x,y));break;case '=':p=Popstack(op_t,p);cin>>ch;break;}}}cout<<"\t表达式结果是:"<<Gettop(op_n)<<endl;return 0;}int Initstack(OPND &op_n,OPTR &op_t){op_n.base=new char[MAXSIZE];op_t.base=new char[MAXSIZE];if((op_n.base==NULL) || (op_t.base==NULL)){exit(1);}op_n.top=op_n.base;op_t.top=op_t.base;op_n.num=MAXSIZE;op_t.c=MAXSIZE;return 0;}void Pushstack(OPND &op_n,char ch){if(op_n.top-op_n.base==op_n.num){return;}*op_n.top++=ch;cout<<ch<<" 入数字栈"<<endl;}void Pushstack(OPTR &op_t,char ch){if(op_t.top-op_t.base==op_t.c){return;}*op_t.top++=ch;cout<<ch<<" 入操作符"<<endl;}char Popstack(OPND &op_n,char ch)if(op_n.top==op_n.base){exit(1);}ch=*--op_n.top;cout<<ch<<" 出数字栈"<<endl;return ch;}char Popstack(OPTR &op_t,char ch){if(op_t.top==op_t.base){exit(1);}ch=*--op_t.top;cout<<ch<<" 出字符栈"<<endl;return ch;}char Gettop(OPTR op_t){char x;if(op_t.top==op_t.base){exit(1);}x=*(op_t.top-1);cout<<"得到操作符栈顶"<<x<<endl;return x;}char Gettop(OPND op_n){char x;if(op_n.top==op_n.base){exit(1);}x=*(op_n.top-1);cout<<"得到操作数栈顶"<<x<<endl;return x;}int In(char ch)if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='('||ch==')'||ch=='#') {return 1;}else{return 0;}}char Precede(char x,char y){if(x=='+' || x=='-'){if(y=='+' || y=='-' || y==')' || y=='#'){return '>';}else{return '<';}}if(x=='*'||x=='/'){if(y=='('){return '<';}else{return '>';}}if(x=='('){if(y==')'){return '=';}else if(y=='+'||y=='-'||y=='*'||y=='/'||y=='('){return '<';}}if(x==')'){if(y!='('){return '>';}}if(x=='#'){if(y=='#'){return '=';}else if(y!=')'){return '<';}}}char operate(char z,char x,char y) {if(x=='+'){return (z-'0') + (y-'0')+48;}if(x=='-'){return (z-'0') - (y-'0')+48;}if(x=='*'){return (z-'0')* (y-'0')+48;}if(x=='/'){return (z-'0')/ (y-'0')+48;}}*//*#include<iostream>using namespace std;int main(){char a[10];char *b[10];char **c[10];return 0;}*//*#include<iostream>using namespace std;char f(char x,char y){return (x-'0') * (y-'0')+48;}int main(){char a='3',b='5';char p=f(a,b);cout<<p<<endl;return 0;}*///数列出队/*#include<iostream>#include<stdlib.h>using namespace std;typedef struct Qnode{int num;struct Qnode *next;}Qnode,*Queueptr;typedef struct{Queueptr front;Queueptr rear;}LinkQueue;int InitQueue(LinkQueue &Q);void EnQueue(LinkQueue &Q,int x); int DeQueue(LinkQueue &Q,int p); int main(){LinkQueue Q;InitQueue(Q);int x,i,y,num=0,e;cout<<"请输入总人数:";cin>>x;for(i=1;i<=x;i++){EnQueue(Q,i);}cout<<"请输入第几个数淘汰:";cin>>y;{for(i=0;i<y;i++){if(i!=y-1){e=DeQueue(Q,e);EnQueue(Q,e);}else{DeQueue(Q,e);num++;}}if(num==x-1){break;}}e=DeQueue(Q,e);cout<<"最后剩下的是:"<<e<<endl;return 0;}int InitQueue(LinkQueue &Q){Q.front=new Qnode;Q.rear=Q.front;if(Q.front==NULL){exit(1);}Q.front->next=NULL;}void EnQueue(LinkQueue &Q,int x){Qnode *p=new Qnode;if(!p){exit(1);}p->num=x;p->next=NULL;Q.rear->next=p;}int DeQueue(LinkQueue &Q,int e) {Qnode *p;if(Q.rear==Q.front){exit(0);}p=Q.front->next;e=p->num;Q.front->next=p->next;if(Q.rear==p){Q.front=Q.rear;}delete p;return e;}*//*二叉树#include<iostream>#include<stdlib.h>using namespace std;typedef struct BiTNode{char date;struct BiTNode *lchild,*rchild; }BiTNode,*BiTree;void CreateBiTree(BiTree &T);int Depth(BiTree T);int NodeCount(BiTree T);int LeavesNodeCount(BiTree T);int PreOrderTraverse(BiTree T);int InOrderTraverse(BiTree T);int PostOrderTraverse(BiTree T); int main(){BiTree T;CreateBiTree(T);cout<<"二叉树的深度为:"<<Depth(T)<<endl;cout<<"二叉树中结点个数为:"<<NodeCount(T)<<endl;cout<<"二叉树中叶子结点个数为:"<<LeavesNodeCount(T)<<endl;cout<<"先序遍历:";PreOrderTraverse(T);cout<<"\n中序遍历:";InOrderTraverse(T);cout<<"\n后序遍历:";PostOrderTraverse(T);cout<<endl;return 0;}void CreateBiTree(BiTree &T){cout<<"请为该节点赋值:";char ch;cin>>ch;if(ch=='#'){T=NULL;}else{T =new BiTNode;T->date=ch;CreateBiTree(T->lchild);CreateBiTree(T->rchild);}}int Depth(BiTree T){int m,n;if(T==NULL){return 0;}else{m=Depth(T->lchild);n=Depth(T->rchild);if(m>n){return m+1;}else{return n+1;}}}int NodeCount(BiTree T){if(T==NULL){return 0;}else{return NodeCount(T->lchild)+NodeCount(T->rchild)+1;}}int LeavesNodeCount(BiTree T){if(T==NULL){return 0;}else if(T->lchild==NULL && T->rchild==NULL){return 1;}else{return LeavesNodeCount(T->lchild)+LeavesNodeCount(T->rchild);}}int PreOrderTraverse(BiTree T){if(T!=NULL){cout<<T->date;PreOrderTraverse(T->lchild);PreOrderTraverse(T->rchild);}}int InOrderTraverse(BiTree T){if(T!=NULL){InOrderTraverse(T->lchild);cout<<T->date;InOrderTraverse(T->rchild);}}int PostOrderTraverse(BiTree T){if(T!=NULL){PostOrderTraverse(T->lchild);PostOrderTraverse(T->rchild);cout<<T->date;}}请为该节点赋值:-请为该节点赋值:+请为该节点赋值:a请为该节点赋值:#请为该节点赋值:#请为该节点赋值:*请为该节点赋值:b请为该节点赋值:#请为该节点赋值:#请为该节点赋值:-请为该节点赋值:c请为该节点赋值:#请为该节点赋值:#请为该节点赋值:d请为该节点赋值:#请为该节点赋值:#请为该节点赋值:/请为该节点赋值:e请为该节点赋值:#请为该节点赋值:#请为该节点赋值:f请为该节点赋值:#请为该节点赋值:#二叉树的深度为:5二叉树中结点个数为:11二叉树中叶子结点个数为:6先序遍历:-+a*b-cd/ef中序遍历:a+b*c-d-e/f后序遍历:abcd-*+ef/-Process returned 0 (0x0) execution time : 76.214 s Press any key to continue.*//*#include<iostream>#include<stdlib.h>#include<string.h>using namespace std;typedef struct{int weiget;int parent,lchild,rchild;}HTNode,*HuffmanTree;typedef char** HuffmanCode;void creat(HuffmanTree &HT,int n);void Select(HuffmanTree HT,int k,int &min1,int &min2); void creatcode(HuffmanTree HT,HuffmanCode &HC,int n); int min(HuffmanTree HT,int k);int main(){int n;cout<<"请输入叶子节点的个数:";cin>>n;HuffmanTree HT;creat(HT,n);HuffmanCode HC;creatcode(HT,HC,n);return 0;}void creat(HuffmanTree &HT,int n){if(n<1){exit(1);}int m=2*n-1,i;HT=new HTNode[m+1];for( i=1;i<=m;i++){HT[i].parent=0;HT[i].lchild=0;HT[i].rchild=0;}for(i=1;i<=n;i++){cout<<"请输入权值:";cin>>HT[i].weiget;}int s1,s2;for(i=n+1;i<=m;i++) //通过n-1次选择来合并创建{Select(HT,i-1,s1,s2);HT[s1].parent=i; //赋值,作为删除的标记HT[s2].parent=i;cout<<"s1:"<<s1<<" s2:"<<s2<<endl;HT[i].lchild=s1; //生成新节点HT[i].rchild=s2;HT[i].weiget=HT[s1].weiget+HT[s2].weiget;}}void Select(HuffmanTree HT,int k,int &min1,int &min2){min1=min(HT,k);min2=min(HT,k);}int min(HuffmanTree HT,int k){int i=0;int min;//存放weight最小且parent为-1的元素的序号int min_wei;//存放权值while(HT[i].parent!=0){i++;}min_wei=HT[i].weiget;min=i;for(;i<=k;i++){if(HT[i].weiget<min_wei && HT[i].parent==0){min_wei=HT[i].weiget;min=i;}}HT[min].parent=1;return min;}void creatcode(HuffmanTree HT,HuffmanCode &HC,int n){HC =new char *[n+1];char *cd=new char[n];cd[n-1]='\0';int i,start;//start指向最后,即编码结束符的位置int current,father;for(i=1;i<=n;i++){start=n-1;current=i;father=HT[i].parent;while(father!=0){--start;if(HT[father].lchild==current){cd[start]='0';}else{cd[start]='1';}current=father;father=HT[father].parent;}HC[i]=new char[n-start];strcpy(HC[i],&cd[start]);cout<<HT[i].weiget<<"对应的编码是:"<<HC[i]<<endl;}delete cd;}请输入叶子节点的个数:5请输入权值:1请输入权值:2请输入权值:3请输入权值:4请输入权值:5s1:1 s2:2s1:3 s2:6s1:4 s2:5s1:7 s2:81对应的编码是:0102对应的编码是:0113对应的编码是:004对应的编码是:105对应的编码是:11Process returned 0 (0x0) execution time : 4.003 s Press any key to continue.*///折半查找#include<iostream>#include<stdio.h>using namespace std;#define ENDFLAG 10000typedef int KeyType;typedef char* InfoType;typedef struct{KeyType key;InfoType otherinfo;}ElemType;typedef struct{ElemType *R;int length;}SSTable;void CreateSTable(SSTable &ST,int n){int i;ST.R=new ElemType[n+1];for(i=1;i<=n;i++){cout<<"请输入"<<i<<"个测试数据:";cin>>ST.R[i].key;}ST.length=n;}int Search_Bin1(SSTable ST,KeyType key){int low,high,mid;low=1;high=ST.length;while(low<=high){mid=(low+high)/2;if(key==ST.R[mid].key){return mid;}else if(key<ST.R[mid].key){high=mid-1;}else{low=mid+1;}}return 0;}int Search_Bin2(SSTable ST,int low,int high,KeyType key) {int mid;if(low>high){return 0;}mid=(low+high)/2;printf("%d+++++",key==ST.R[mid].key);if(key==ST.R[mid].key){return mid;}else if(key<ST.R[mid].key){return Search_Bin2(ST,low,mid-1,key);}else{return Search_Bin2(ST,mid+1,high,key);}}int main(){int n;KeyType key;SSTable ST;cout<<"请输入静态查找表长:";cin>>n;CreateSTable(ST,n);cout<<"请输入待查记录的关键字:";cin>>key;cout<<"Search_Bin1算法计算的位置为:"<<Search_Bin1(ST,key)<<endl;cout<<"Search_Bin2算法计算的位置为:"<<Search_Bin2(ST,1,ST.length,key)<<endl;return 0;}/*请输入静态查找表长:5请输入1个测试数据:1请输入2个测试数据:2请输入3个测试数据:3请输入4个测试数据:4请输入5个测试数据:5请输入待查记录的关键字:3Search_Bin1算法计算的位置为:3Search_Bin2算法计算的位置为:3Process returned 0 (0x0) execution time : 8.620 sPress any key to continue.*//*#include<iostream>using namespace std;typedef struct{int key;}ElemType;typedef struct BSTNode{ElemType date;struct BSTNode *lchild,*rchild;}BSTNode,*BSTree;void Create(BSTree &T);void Insert(BSTree &T,ElemType e);int InOrderTraverse(BSTree T);int main(){BSTree T;Create(T);InOrderTraverse(T);cout<<"\n中序遍历:";return 0;}void Create(BSTree &T){T=NULL;ElemType e;cout<<"请为节点赋值:(0为结束条件)";cin>>e.key;while(e.key!=0){Insert(T,e);cout<<"请为节点赋值:(0为结束条件)";cin>>e.key;}}void Insert(BSTree &T,ElemType e){if(!T){BSTree S;S=new BSTNode;S->date=e;S->lchild=NULL;S->rchild=NULL;T=S;}else if(e.key<T->date.key){Insert(T->lchild,e);}else{Insert(T->rchild,e);}}int InOrderTraverse(BSTree T){if(T!=NULL){InOrderTraverse(T->lchild);cout<<T->date.key<<" ";InOrderTraverse(T->rchild);}return 0;}请为节点赋值:(0为结束条件)12请为节点赋值:(0为结束条件)7请为节点赋值:(0为结束条件)17请为节点赋值:(0为结束条件)11请为节点赋值:(0为结束条件)16请为节点赋值:(0为结束条件)2请为节点赋值:(0为结束条件)13请为节点赋值:(0为结束条件)9请为节点赋值:(0为结束条件)21请为节点赋值:(0为结束条件)4请为节点赋值:(0为结束条件)02 4 7 9 11 12 13 16 17 21中序遍历:Process returned 0 (0x0) execution time : 23.808 s Press any key to continue.*/。
【数据结构】线性表顺序表详解和代码实例
【数据结构】线性表顺序表详解和代码实例线性表(List)是零个或者多个数据元素的有限序列.⾸先它是⼀个序列.⾥⾯的元素是有顺序的,如果有多个元素,除开头和结尾以外的元素都有⼀个前驱和⼀个后继.⽽开头元素只有后继,结尾元素只有前驱.其次线性表是有限的,也就是⾥⾯的元素个数是有限的。
1ADT 线性表(List)2Data3线性表的数据对象集合为{a1, a2, a3, ......, an},每个元素类型为DataType。
4Operation5InitList(L); //初始化线性表6 IsEmptyList(L); //判断线性表是否为空7 ClearList(L); //清空线性表8 GetElemList(L, i, *e); //获取第i个位置的数据9 SearchList(L, e); //查找与数据e相等的元素10 InsertNodeList(L, i, e);//在第i个位置插⼊元素11 DeleteNodeList(L, i, *e);//删除第i个位置的元素,e获取删除元素12 GetLengthList(L); //获取线性表的长度13endADT关于线性表的基本操作就上⾯⼏种,还有⼏个例如线性表的排序,合并,逆序等等操作。
为了⽂章篇幅,就下次再介绍了。
线性表的顺序存储结构,就是指 ⽤⼀段地址连续的存储单元⼀次存储线性表的数据元素。
学过⾼级语⾔的朋友,相信对数组这玩意⼉都不会陌⽣吧。
数组就是⼀种顺序存储结构。
链式存储结构就是可以⽤⼀组任意的内存单元存储线性表中的元素。
与顺序存储不同的是,这组内存单元可以是连续的,也可以是不连续的。
这就意味着,元素可以存储在内存的任意位置。
正因为如此,在链式结构中,每个元素不仅要存它的信息,还需要存储它后继元素的存储地址。
我们把存储元素信息的域称为数据域,⽽把存储后继元素地址的域称为指针域。
由这两部分共同组成的数据元素ai,则可以称之为节点(Node)。
python实现顺序表的简单代码
python实现顺序表的简单代码顺序表即线性表的顺序存储结构。
它是通过⼀组地址连续的存储单元对线性表中的数据进⾏存储的,相邻的两个元素在物理位置上也是相邻的。
⽐如,第1个元素是存储在线性表的起始位置LOC(1),那么第i个元素即是存储在LOC(1)+(i-1)*sizeof(ElemType)位置上,其中sizeof(ElemType)表⽰每⼀个元素所占的空间。
下⾯是顺序表的python实现:#coding:utf-8'''author:xzfreewind'''class SeqList(object):def __init__(self,max=10):self.max = max #默认顺序表最多容纳10个元素#初始化顺序表数组self.num = 0self.date = [None] * self.maxdef is_empty(self): #判定线性表是否为空return self.num is 0def is_full(self): #判定线性表是否全满return self.num is self.max#获取线性表种某⼀位置的元素def __getitem__(self, i):if not isinstance(i,int): #如果i不为int型,则判定输⼊有误,即Type错误raise TypeErrorif 0<= i < self.num: #如果位置i满⾜条件,即在元素个数的范围内,则返回相对应的元素值,否则,超出索引,返回IndexErrorreturn self.date[i]else:raise IndexError#修改线性表种某⼀位置的元素def __setitem__(self, key, value):if not isinstance(key,int): #如果key不为int型,则判定输⼊有误,即Type错误raise TypeErrorif 0<= key <self.num: #如果位置key满⾜条件,即在元素个数的范围内,则返回相对应的元素值,否则,超出索引,返回IndexErrorself.date[key] = valueelse:raise IndexError#按值查找元素的位置def getLoc(self,value):n = 0for j in range(self.num):if self.date[j] == value:return jif j == self.num:return -1 #如果遍历顺序表还未找到value值相同的元素,则返回-1表⽰顺序表种没有value值的元素#统计线性表中元素的个数def Count(self):return self.num#表末尾插⼊操作def appendLast(self,value):if self.num >= self.max:print 'The list is full'returnelse:self.date[self.num] = valueself.num += 1#表任意位置插⼊操作:def insert(self,i,value):if not isinstance(i,int):raise TypeErrorif i < 0 and i > self.num:raise IndexErrorfor j in range(self.num,i,-1):self.date[j] = self.date[j-1]self.date[i] = valueself.num += 1#删除某⼀位置的操作def remove(self,i):if not isinstance(i,int):raise TypeErrorif i < 0 and i >=self.num:raise IndexErrorfor j in range(i,self.num):self.date[j] = self.date[j+1]self.num -= 1#输出操作def printList(self):for i in range(0,self.num):print self.date[i]#销毁操作def destroy(self):self.__init__()以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
数据结构c++顺序表、单链表的基本操作,查找、排序代码
} return 0; }
实验三 查找
实验名称: 实验3 查找 实验目的:掌握顺序表和有序表的查找方法及算法实现;掌握二叉排序 树和哈希表的构造和查找方法。通过上机操作,理解如何科学地组织信 息存储,并选择高效的查找算法。 实验内容:(2选1)内容1: 基本查找算法;内容2: 哈希表设计。 实验要求:1)在C++系统中编程实现;2)选择合适的数据结构实现查 找算法;3)写出算法设计的基本原理或画出流程图;4)算法实现代码 简洁明了;关键语句要有注释;5)给出调试和测试结果;6)完成实验 报告。 实验步骤: (1)算法设计 a.构造哈希函数的方法很多,常用的有(1)直接定址法(2)数字分析法;(3) 平方取中法;(4)折叠法;( 5)除留余数法;(6)随机数法;本实验采用的是除 留余数法:取关键字被某个不大于哈希表表长m的数p除后所得余数为哈 希地址 (2)算法实现 hash hashlist[n]; void listname(){ char *f; int s0,r,i; NameList[0].py="baojie"; NameList[1].py="chengቤተ መጻሕፍቲ ባይዱoyang"; ……………………………… NameList[29].py="wurenke"; for(i=0;i<q;i++){s0=0;f=NameList[i].py; for(r=0;*(f+r)!='\0';r++) s0+=*(f+r);NameList[i].k=s0; }} void creathash(){int i;
v[k-1]=v[k]; nn=nn-1; return ; } int main() {sq_LList<double>s1(100); cout<<"第一次输出顺序表对象s1:"<<endl; s1.prt_sq_LList(); s1.ins_sq_LList(0,1.5); s1.ins_sq_LList(1,2.5); s1.ins_sq_LList(4,3.5); cout<<"第二次输出顺序表对象s1:"<<endl; s1.prt_sq_LList(); s1.del_sq_LList(0); s1.del_sq_LList(2); cout<<"第三次输出顺序表对象s1:"<<endl; s1.prt_sq_LList(); return 0; } 运行及结果:
顺序表
while(i<L_pointer->length && strcmp(L_pointer->Element[i].name,))
i++;
if(i==L_pointer->length) return -1;
else return i+1;
}
int delete_seqlist(seqlist*L_pointer,int i)
if(insert_last(&list,dc)!=ok)
printf("插入失败\n");
break;
case 2:printf("请输入要查询的订餐者姓名\n");scanf("%s",);
loca=location_seqlist(&list,dc);
if(loca!=-1)printf("查找成功");break;
L_pointer->Element[L_pointer->length].sum=x.sum;
strcpy(L_pointer->Element[L_pointer->length].time,x.time );
L_pointer->length+&
int location_seqlist(seqlist *L_pointer,Elemtype x)
case 3:printf("请输入要删除的订餐者姓名\n");scanf("%s",);
loca=location_seqlist(&list,dc);
if(loca!=-1)
顺序表的查找完整实现代码
i--;
return i;
}
struct node{
int key;
struct nodct node *ST,int key)
{
struct node *m = ST;
while(m->next!=NULL&&m->key!=key)
else
high = mid-1;
}
return 0;
}
void getData(STable *t)
{
char *fp = ".\\stu.dat";
int i=1;
fstream ff(fp,ios::in|ios::trunc);
ff.read((char *)&(t->length),4);
#define LE(a,b) ((a) <= (b))
typedef int keyType;
typedef struct {
int key;
float info;
}sTable;
int seq_search(sTable ST[],int n,int key)
{
ST[0].key = key;
int i = n;
i++;
}
fa.close();
int j,k;
ST.elem = stu;
getData(&ST);
cout<<"class people is "<<ST.length<<endl;
cout<<"cin the k"<<endl;
三元组顺序表
矩阵转置算法及代码实现(三元组顺序表)矩阵的转置实际上就是将数据元素的行标和列标互换,即T(i,j) = M(j,i) 。
例如:图1 矩阵的转置相应地,三元组表转变为:图2 三元组表矩阵的转置,经历了三个步骤:矩阵的行数n 和列数m 的值交换;将三元组中的i和j调换;转换之后的表同样按照行序(置换前的列序)为主序,进行排序;实现三元组的转换,重点在第三步,实现算法有两种。
普通算法普通算法的实现过程为:将矩阵的行数和列数进行调换;遍历表 a 的j 列(查找j 的值,从 1 一直到未转置之前的矩阵的列数m ),遍历的过程,就可以自动存储为表b 的形式。
因为在表 a 中i 列的数值是从小到大的,在根据j 列由上到下的遍历时,i 列同样也是有序的。
实现代码:TSMatrix transposeMatrix(TSMatrix M,TSMatrix T){//行和列置换T.m=M.n;T.n=M.m;T.num=M.num;if (T.num) {int q=0;//依次遍历M矩阵的列(从1开始),的遍历的过程中将行标和列标置换,得到置换后的三元表Tfor (int col=1;col<=M.m; col++) {for (int p=0; p<M.num; p++) {if (M.data[p].j==col) {T.data[q].i=M.data[p].j;T.data[q].j=M.data[p].i;T.data[q].data=M.data[p].data;q++;}}}}return T;}此算法的时间复杂度关键在于嵌套的两个for 循环,时间复杂度为O(m*num),和矩阵的列数以及非0 元素的个数的乘积成正比,如果稀疏矩阵的非0 元素很多的情况,使用这个算法,虽然一定程度上节省了空间,但是时间复杂度会很高。
快速转置算法快速转置算法在普通算法的基础上,对遍历存储的过程做了改进。
首先将每一列中非0 元素的个数对应地存储在一个数组(数组名为array)中。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
if(lp->length<=0) { printf("No data!\n"); return; } for(i=0;i<lp->length;i++) printf("%d ",lp->data[i]); printf("\nlength of the list is: %d",lp->length); } void insertlist(list_type *lp,int i,int a) //插入一个元素 { int j; if(lp->length>=MAXNUM) { printf("the list is full,can not insert."); } if(i<1 || i>lp->length+1) { printf("\n%d is invalid value",i); } for(j=lp->length-1;j>i-1;j--) lp->data[j+1]=lp->data[j]; lp->data[i]=a; lp->length++; } int deletelist(list_type *lp,int i) //删除一个元素 { int j; if(i<1 || i>lp->length) { printf("elem not exist"); return(false); } for(j=i;j<lp->length;j++)
printf("\nlist after delete:\n"); printlist(&list); printf("\ndelete negative nums:\n"); delete_negative(&list); printlist(&list); }
lp->data[j-1]=lp->data[j]; lp->length--; return(true); } void delete_negative(list_type *l) //删除所有的负数 { int i=0,k; for(;i<l->length;i++) { if(l->data[i]<0) { for(int j=i;j<l->length-1;j++) l->data[i]=l->data[i+1]; l->length--; i--; } } } void main() { list_type list; int i,j,a; createlist(&list); printlist(&list); printf("\ninsert:Enter i and data:\n"); scanf("%d%d",&i,&a); insertlist(&list,i,a); printf("\nlist after insert:\n"); printlist(&list); printf("\ndelete:Enter j:\n"); scanf("%d",&j); deletelist(&list,j);