数据结构实验指导书源代码

合集下载

数据结构上机实验源代码

数据结构上机实验源代码

数据结构上机实验源代码栈的应用十进制数转换为八进制数,逆序输出所输入的数实验代码://stack.h,头文件class stack{public:stack();bool empty()const;bool full()const;error_code gettop(elementtype &x)const;error_code push(const elementtype x);error_code pop();private:int count;elementtype data[maxlen];};stack::stack(){count=0;}bool stack::empty()const{return count==0;}bool stack::full()const{return count==maxlen;}error_code stack::gettop(elementtype &x)const{if(empty())return underflow;else{x=data[count-1];return success;}}error_code stack::push(const elementtype x){if(full())return overflow;data[count]=x;count++;return success;}error_code stack::pop(){if(empty())return underflow;count--;return success;}//主程序#include<iostream.h>enum error_code{overflow,underflow,success};typedef int elementtype;const int maxlen=20;#include"stack.h"void read_write() //逆序输出所输入的数{stack s;int i;int n,x;cout<<"please input num int n:";cin>>n;for(i=1;i<=n;i++){cout<<"please input a num:";cin>>x;s.push(x);}while(!s.empty()){s.gettop(x);cout<<x<<" ";s.pop();}cout<<endl;}void Dec_to_Ocx(int n) //十进制转换为八进制{stack s1;int mod,x;while(n!=0){mod=n%8;s1.push(mod);n=n/8;}cout<<"the ocx of the dec is:";while(!s1.empty()){s1.gettop(x);cout<<x;s1.pop();}cout<<endl;}void main(){int n;// read_write();cout<<"please input a dec:";cin>>n;Dec_to_Ocx(n);}队列的应用打印n行杨辉三角实验代码://queue.hclass queue{public:queue(){count=0;front=rear=0;}bool empty(){return count==0;}bool full(){return count==maxlen-1;}error_code get_front(elementtype &x){if(empty())return underflow;x=data[(front+1)%maxlen];return success;}error_code append(const elementtype x){if(full())return overflow;rear=(rear+1)%maxlen;data[rear]=x;count++;return success;}error_code serve(){if(empty())return underflow;front=(front+1)%maxlen;count--;return success;}private:int count;int front;int rear;int data[maxlen];};//主程序#include<iostream.h>enum error_code{overflow,underflow,success};typedef int elementtype;const int maxlen=20;#include"queue.h"void out_number(int n) //打印前n行的杨辉三角{int s1,s2;int i;int j;int k;queue q;for(i=1;i<=(n-1)*2;i++)cout<<" ";cout<<"1 "<<endl;q.append(1);for(i=2;i<=n;i++){s1=0;for(k=1;k<=(n-i)*2;k++)cout<<" ";for(j=1;j<=i-1;j++){q.get_front(s2);q.serve();cout<<s1+s2<<" ";q.append(s1+s2);s1=s2;}cout<<"1 "<<endl;q.append(1);}}void main(){int n;cout<<"please input n:";cin>>n;out_number(n);}单链表实验实验目的:实验目的(1)理解线性表的链式存储结构。

数据结构试验完整代码

数据结构试验完整代码

数据结构实验完整代码目录一、顺序存储的线性表 (2)二、单链存储的线性表 (4)三、栈 (7)四、队列 (8)五、二叉树的建立和遍历 (10)六、霍夫曼树 (11)七、图的建立和遍历 (17)图的邻接矩阵表示 (17)图的邻接表表示 (20)八、图的最小生成树 (23)九、图的最短路径 (28)十、顺序查找表 (31)十一、二叉排序树的查找 (34)十二、哈希表 (36)十三、插入排序 (41)十四、交换排序-冒泡排序 (44)十五、交换排序-快速排序 (45)十六、简单选择排序 (45)十七、堆排序 (46)一、顺序存储的线性表typedef struct{char name[10];char no[10];double grade;}Student;typedef struct{Student *elem;int length;int listsize;}SqList;void Display(SqList *L){int i;for (i=0;i<L->length ;i++){cout<<i+1<<":姓名"<<L->elem[i].name<<",学号:"<<L->elem[i].no<<",成绩:"<<L->elem[i].grade <<endl;}cout<<"请选择菜单项:";}SqList *CreateList(){SqList *L;L=(SqList*)malloc(sizeof(SqList));if(!L) cout<<"建立线性表失败!";else cout<<"建立线性表成功!";return(L);}int InitList(SqList *L){int i;char name[10],no[10];double grade;L->elem=(Student *)malloc(ListInitSize * sizeof(Student));if (!(L->elem)) cout<<"初始化表失败!";L->length = 0;L->listsize = ListInitSize;cout<<"请输入要录入信息的学生个数:"<<endl;cin>>i;if (i>(L->listsize)){L->elem =(Student *)realloc(L->elem ,i*sizeof(Student));}for (int j=0;j<i;j++){cout<<"请输入第"<<j+1<<"个学生的信息:"<<endl;cin>>name>>no>>grade;strcpy((L->elem+L->length)->name,name);strcpy((L->elem+L->length)->no,no);(L->elem+L->length)->grade =grade;L->length ++;}cout<<"信息录入完成!";return 0;}int Insert(SqList *l){Student e;int i,j;Student *newbase;cout<<"请输入要插入的位置:";cin>>j;j--;cout<<"请输入学生信息:";cin>>>>e.no>>e.grade;if(l->length==l->listsize){newbase=(Student*)realloc(l->elem,(l->listsize+ListIncreasement)*sizeof(Studen t));if(!newbase){cout<<"出错!";return 0;}l->elem=newbase;l->listsize+=ListIncreasement;}for(i=l->length;i>=j;i--){l->elem[i+1] = l->elem[i];}l->elem[j]=e;l->length++;cout<<"插入成功!";return 0;}int Delect(SqList *L){int i,j;cout<<"输入删除信息的位置:";cin>>j;j--;cout<<"删除的信息为:姓名:"<<L->elem[j].name<<",学号:"<<L->elem[j].no<<"成绩:"<<L->elem[j].grade<<endl;for(i=j+1;i<=L->length;i++){L->elem[i-1]=L->elem[i];}L->length--;cout<<"请按回车继续"<<endl;getchar();getchar();cout<<"删除成功!";return 0;}二、单链存储的线性表typedef struct Student{char name[10];char no[10];double grade;}Student;typedef struct LNode{Student data;LNode *next;}LNode,*LinkList;void CreateList(LinkList &l){l=(LinkList)malloc(sizeof(LNode));if (!l) cout<<"建立失败。

数据结构与算法实验源代码

数据结构与算法实验源代码

数据结构与算法实验源代码数据结构与算法实验源代码1.实验目的本实验旨在通过实践,加深对数据结构与算法的理解与应用能力,掌握数据结构和算法的基本概念与原理,并能够运用所学知识解决实际问题。

2.实验材料●一台已安装好编译器的计算机●数据结构与算法实验源代码文件3.实验环境配置在实验开始之前,必须确保计算机上已安装好以下环境:●编译器(可以是C++、Java等)●数据结构与算法实验源代码文件4.实验内容及步骤4.1 实验一:线性表4.1.1 实验目的通过实现线性表的相关操作,加深对线性表及其操作的理解,并能够灵活应用。

4.1.2 实验步骤1.实现线性表的初始化函数2.实现线性表的插入操作3.实现线性表的删除操作4.实现线性表的查找操作5.实现线性表的排序操作6.实现线性表的输出操作7.编写测试代码,对线性表进行测试4.1.3 实验结果与分析进行若干测试用例,验证线性表的正确性,并分析算法的时间复杂度与空间复杂度。

4.2 实验二:栈与队列4.2.1 实验目的通过实现栈与队列的相关操作,加深对栈与队列的理解,并掌握栈与队列的应用场景。

4.2.2 实验步骤1.实现栈的初始化函数2.实现栈的入栈操作3.实现栈的出栈操作4.实现栈的查看栈顶元素操作5.实现队列的初始化函数6.实现队列的入队操作7.实现队列的出队操作8.实现队列的查看队首元素操作4.2.3 实验结果与分析进行若干测试用例,验证栈与队列的正确性,并分析算法的时间复杂度与空间复杂度。

(继续添加实验内容及步骤,具体根据实验项目和教学要求进行详细分析)5.实验附件本文档所涉及的实验源代码文件作为附件随文档提供。

6.法律名词及注释6.1 版权:著作权法所规定的权利,保护作品的完整性和原创性。

6.2 开源:指软件可以被任何人免费使用、分发和修改的一种软件授权模式。

(继续添加法律名词及注释)。

数据结构实验二的源代码

数据结构实验二的源代码

#include<stdio.h>#include<math.h>#include<string.h>#include<stdlib.h>#include<ctype.h>//判断是否为字符函数的头文件typedef int elemtype;//声明一个别名char ch[8] = { '+' , '-' , '*' , '/' ,'(' , ')' , '#' }; //把符号转换成字符数组int f1[7] = { 3,3,5,5,1,6,0 }; //栈内元素优先级int f2[7] = { 2,2,4,4,6,1,0 }; //栈外元素优先级int n = 0;typedef struct sqstack//顺序栈结构{elemtype stack[100];int top;}sqstsck;void Initstack(sqstack *s)//初始化{s->top = 0;}void Push(sqstack *s, elemtype x)//入栈{s->top++;s->stack[s->top] = x;}void Pop(sqstack *s, elemtype *x)//出栈{*x = s->stack[s->top];s->top--;}elemtype Gettop(sqstack s)//取栈顶元素{return s.stack[s.top];}elemtype cton(char c)//把操作符转换为相应数字{switch (c){case'+': return 0;case'-': return 1;case'*': return 2;case'/': return 3;case'(': return 4;case')': return 5;default: return 6;}}char Compare(char c1, char c2)//比较字符优先级{int i1 = cton(c1);int i2 = cton(c2); //把字符变成数字if (f1[i1] > f2[i2]) return'>'; //通过原来的设定找到优先级else if (f1[i1] < f2[i2]) return'<';else return'=';}int Operate(elemtype a, elemtype t, elemtype b)//四则运算{int sum;switch (t){case 0: sum = a + b; break;case 1: sum = a - b; break;case 2: sum = a * b; break;default: sum = a / b;}return sum;}int Expression()//主要表达式函数{char c;int i = 0, sum = 0;int k = 1, j = 1; //设置开关变量elemtype x, t, a, b;sqstack OPTR, OPND;Initstack(&OPTR);Push(&OPTR, cton('#')); //‘#’压入栈Initstack(&OPND);c = getchar();while (c != '#' || ch[Gettop(OPTR)] != '#'){if (isdigit(c)) //判断c是否为数字{sum = 0;while (isdigit(c)){if (!j) //j用来进行字符串转换判断,j为0转换{sum = sum * 10 - (c - '0');}else sum = sum * 10 + (c - '0'); //字符c转化成对应数字c = getchar();}Push(&OPND, sum);j = 1;}else if (k){switch (Compare(ch[Gettop(OPTR)], c)){case'<': Push(&OPTR, cton(c)); //把字符整型化,然后压入操作符栈c = getchar();break;case'=': Pop(&OPTR, &x); //操作符栈顶元素出栈c = getchar();break;case'>': Pop(&OPTR, &t); //操作符栈顶元素出栈Pop(&OPND, &b); //操作数栈顶元素出栈Pop(&OPND, &a); //操作数栈顶元素出栈Push(&OPND, Operate(a, t, b));break;}}}return (Gettop(OPND));}void main(){int result;printf("请输入'#'号结束:\n");result =Expression();printf("结果为:%d\n", result);system("color 6");system("pause");}。

《数据结构》实验指导书(源代码)

《数据结构》实验指导书(源代码)

实验一线性表的链式存储结构一、实验目的:1.掌握线性表的链式存储结构。

2.熟练地利用链式存储结构实现线性表的基本操作。

3.能熟练地掌握链式存储结构中算法的实现。

二、实验内容:1.用头插法或尾插法建立带头结点的单链表。

2.实现单链表上的插入、删除、查找、修改、计数、输出等基本操作。

三、实验要求:1. 根据实验内容编写程序,上机调试、得出正确的运行程序。

2. 写出实验报告(包括源程序和运行结果)。

四、实验学时:2学时五、实验步骤:1.进入编程环境,建立一新文件;2. 参考以下相关内容,编写程序,观察并分析输出结果。

①定义单链表的数据类型,然后将头插法和尾插法、插入、删除、查找、修改、计数、输出等基本操作都定义成子函数的形式,最后在主函数中调用它,并将每一种操作前后的结果输出,以查看每一种操作的效果。

②部分参考程序//单链表的建立(头插法),插入,删除,查找、修改、计数、输出#include<iostream.h>#define elemtype intstruct link{ elemtype data;//元素类型link *next; //指针类型,存放下一个元素地址};//头插法建立带头结点的单链表link *hcreat(){ link s,p;elemtype i;cout<<”输入多个结点数值(用空格分隔),为0时算法结束”;cin>>i;p=new link;p->next=NULL;while(i) //当输入的数据不为0时,循环建单链表{s=new link;s->data=i;s->next=p->next;p->next=s;cin>>i; }return p;}//输出单链表void print(1ink *head){1ink *p;p=head->next;while(p->next!=NULL){cout<<p->data<<”->”; //输出表中非最后一个元素p=p->next;}cout<<p->data; //输出表中最后一个元素cout<<endl;}∥在单链表head中查找值为x的结点Link *Locate(1ink *head,elemtype x){Link *p;p=head->next;while((p!=NULL)&&(p->data!=x))p=p->next;return p; }//在head为头指针的单链表中,删除值为x的结点void deletel(1ink *head,elemtype x){1ink *p, *q;q=head;p=head->next;while((p!=NULL)&&(p->data!=x)){q=p;p=p->next;}If(p==NULL) cout<<“要删除的结点不存在”;elseq->next=p ->next;delete(p);}}//在头指针head所指的单链表中,在值为x的结点之后插入值为y的结点void insert(1ink *head,elemtype x,elemtype y){ link *p, *s;s=new link;s->data=y;if(head->next==NULL) //链表为空{head->next=s;s->next=NULL:}p=Locate(head,x);//调用查找算法‘if(p==NULL)cout<<”插入位置非法”:else(s->next=p->next;p->next=s;}}//将单链表p中所有值为x的元素修改成y void change(1ink *p,elemtype x,elemtype y) {link *q;q=p->next;while(q!=NULL){ if(q->data==x) q->data=y;q=q->next;}}void count(1ink *h) //统计单链表中结点个数{1ink *p;int n=0;p=h->next;while(p!=NULL){n++;p=p->next;}return n;}void main(){ int n;elemtype x,y;link *p, *q;p=hcreat(); //头插法建立链表print(p); //输出刚建立的单链表cout<<”请输入要删除的元素”;cin>>y;deletel(p,y);print(p); //输出删除后的结果cout<<”请输入插入位置的元素值(将待插元素插入到它的后面)”; cin>>x;cout<<”请输入待插元素值”;cin>>y;insert(p,x,y);print(p); //输出插入后的结果cout<<”请输入要修改前、后的元素值”;cin>>x>>y;change(p,x,y);print(p);cout<<”请输入要查找的元素值”;cin>>x;q=Locate(p,x);if(q==NULL)cout<<x<<”不在表中,找不到!”<<endl;else cout<<x<<”在表中,已找到!”<<endl;n=count(p);cout<<”链表中结点个数为:”<<n<<endl:}//单链表的建立(尾插法)、插入、删除、查找、修改、计数、输出#include<iostream.h>#define elemtype intstruct link{ elemtype data;//元素类型link *next;//指针类型,存放下-个元素地址};//尾插法建立带头结点的单链表link *rcreat(){link *s, *p, *r;elemtype i;cout<<”输入多个结点数值(用空格分隔),为0时算法结束”; cin>>i;p=r=new link;p->next=NULL;while(i){s=new link;s->data=i;r->next=s;r=s;cin>>i; }r->next=NULL;return p;}//输出单链表void print(1ink *head){link *p;p=head->next;while(p->next!=NULL){cout<<p->data<<"->”; //输出表中非最后一个元素p=p->next;)cout<<p->data; //输出表中最后一个元素cout<<endl;}link *Locate(1ink *head,int x) ∥在单链表中查找第x个结点 {link *p;p=head;int j=0;while((p!=NULL)&&(j<x)){p=p->next; j++;}return p;}void delete I(1ink *head,elemtype x)//在head为头指针的单链表中,删除值为x的结点{link *p, *q;q=head;p=head->next;while((p!=NULL)&&(p->data!=x)){q=p;p=p->next;)if(p==NULL)cout<<”要删除的结点不存在“;else{q->next=p->next;delete(p);} }void insert(1ink *head,int x,elemtype y)//在头指针head所指单链表中,在第x个结点之后插入值为y的结点{link *p, *s;s=new link;s->data=y;if(head->next==NULL)//链表为空{head->next=s;s->next=NULL:}p=Locate(head,x); //调用查找算法if(p==NULL)cout<<”插入位置非法”;else{s->next=p->next;p->next=s;}}void change(1ink *p,elemtype x,elemtype y){∥将单链表P中所有值为x的元素改成值为ylink *q;q=p->next;while(q!=NULL){if(q->data==x)q->data=y;q=q->next;}}void count(1ink *h) //统计单链表中结点个数(1ink *p;int n=0;p=h->next;while(p!=NULL){n++;p=p->next;}retum n;}void main(){ int n;link p,q;p=rcreat();//尾插法建立链表print(p); //输出刚建立的单链表cout<<”请输入要删除的元素”;cin>>y;deletel(p,y);print(p); //输出删除后的结果cout<<”请输入插入位置”;cin>>x;cout<<”请输入待插元素值”;cin>>y;insert(p,x,y);print(p); //输出插入后的结果cout<<”请输入修改前、后的元素值”;cin>>x>>y;change(p,x,y);print(p);cout<<“请输入要查找的元素值”;cin>>x;q=Locate(p ,x);if(q==NULL)cout<<x<<”不在表中,找不到!”<<endl;else cout<<x<<”在表中,已找到!”<<endl;n=count(p);cout<<”链表中结点个数为:”<<n<endl;}六、选作实验试设计一元多项式相加(链式存储)的加法运算。

数据结构课本算法源代码

数据结构课本算法源代码

void Union(List &La, List Lb) { // 算法2.1// 将所有在线性表Lb中但不在La中的数据元素插入到La中int La_len,Lb_len,i;ElemType e;La_len = ListLength(La); // 求线性表的长度Lb_len = ListLength(Lb);for (i=1; i<=Lb_len; i++) {GetElem(Lb, i, e); // 取Lb中第i个数据元素赋给eif (!LocateElem(La, e, equal)) // La中不存在和e相同的数据元素ListInsert(La, ++La_len, e); // 插入}} // unionvoid MergeList(List La, List Lb, List &Lc) { // 算法2.2// 已知线性表La和Lb中的元素按值非递减排列。

// 归并La和Lb得到新的线性表Lc,Lc的元素也按值非递减排列。

int La_len, Lb_len;ElemType ai, bj;int i=1, j=1, k=0;InitList(Lc);La_len = ListLength(La);Lb_len = ListLength(Lb);while ((i <= La_len) && (j <= Lb_len)) { // La和Lb均非空GetElem(La, i, ai);GetElem(Lb, j, bj);if (ai <= bj) {ListInsert(Lc, ++k, ai);++i;} else {ListInsert(Lc, ++k, bj);++j;}}while (i <= La_len) {GetElem(La, i++, ai); ListInsert(Lc, ++k, ai);}while (j <= Lb_len) {GetElem(Lb, j++, bj); ListInsert(Lc, ++k, bj);}} // MergeListStatus InitList_Sq(SqList &L) { // 算法2.3// 构造一个空的线性表L。

数据结构实验指导书源程序附件

数据结构实验指导书源程序附件

附录:实验源程序实验一、线性表操作程序1:顺序存储的线性表和运算#include<stdio.h>#define MAXSIZE 100int list[MAXSIZE];int n;/*insert in a seqlist*/int sq_insert(int list[], int *p_n, int i, int x){int j;if (i<0 || i>*p_n) return(1);if (*p_n==MAXSIZE) return(2);for (j=*p_n+1; j>i; j--)list[j]=list[j-1];list[i]=x;(*p_n)++;return(0);}/*delete in a seq list*/int sq_delete(int list[], int *p_n, int i){int j;if (i<0 || i>=*p_n) return(1);for (j = i+1; j<=*p_n; j++)list[j-1] = list[j];(*p_n)--;return(0);}void main(){int i,x,temp;printf("please input the number for n\n");printf("n=");scanf("%d",&n);for (i=0; i<=n; i++){printf("list[%d]=",i);scanf("%d",&list[i]);}printf("The list before insertion is\n");for (i=0; i<=n; i++) printf("%d ",list[i]);printf("\n");printf("please input the position where you want to insert a value\nposition=");scanf("%d",&i);printf("please input the value you want to insert.\nx=");scanf("%d",&x);temp=sq_insert(list,&n,i,x);switch(temp){case 0:printf("The insertion is successful!\n");printf("The list is after insertion is\n");for(i=0; i<=n; i++) printf("%d ",list[i]);printf("\n");printf("%d\n",n);break;case 1:case 2:printf("The insertion is not successful!\n");break;}/*deleting*/printf("The list before deleting is\n");for (i=0; i<=n; i++) printf("%d ",list[i]);printf("\n");printf("please input the position where you want to delete a value\nposition=");scanf("%d",&i);temp=sq_delete(list,&n,i);switch(temp){case 0:printf("The deleting is successful!\n");printf("The list is after deleting is\n");for(i=0; i<=n; i++) printf("%d ",list[i]);printf("\n");printf("%d",n);break;case 1:printf("The deleting is not successful!");break;}}程序2链式存储的线性表和运算#include<stdio.h>#include<malloc.h>struct node{char data;struct node *next;};typedef struct node NODE;/*This function creates a link_list with N nodes.*/NODE *create_link_list(int n){int i;NODE *head, *p, *q;if (n==0) return NULL;head = (NODE *) malloc(sizeof(NODE));p = head;printf("Please input %d chars for the link list\n",n);for (i=0; i<n; i++){scanf("%c ", &(p->data));q=(NODE *)malloc(sizeof(NODE));printf("test3\n");p->next=q;p=q;}scanf("%c ",&(p->data));getchar();p->next=NULL;return (head);}/*This function inserts a node whose value is b*//*before the node whose value is a, if the node is not exist,*/ /*then insert it at the end of the list*/void insert(NODE **p_head, char a, char b){NODE *p, *q;q = (NODE *)malloc(sizeof(NODE));q->data = b;q->next =NULL;if (* p_head == NULL) * p_head = q;else{p=(NODE*)malloc(sizeof(NODE));p = * p_head;while (p->data != a && p->next != NULL)p = p->next;q->next = p->next;p->next = q;}}/*The function deletes the node whose value is a,*//*if success, return 0, or return 1*/int deletenode(NODE **p_head, char a){NODE *p, *q;q=*p_head;if (q==NULL) return(1);if (q->data == a){* p_head = q->next;free(q);return (0);}else{while (q->data != a && q->next != NULL){p = q;q = q->next;}if (q->data == a){p->next = q->next;free(q);return(0);}else return(1);}}void main(){ NODE *my_head,*p;/* create a link list with m nodes */int m;char ch_a,ch_b;printf("please input the number of nodes for the link_list\nm=");scanf("%d",&m);getchar();printf("test1\n");my_head = (NODE *) malloc(sizeof(NODE));my_head=create_link_list(m);/*Output the link list*/printf("The link list is like:\n");p=my_head;while (p != NULL){printf("%c ",p->data);p=p->next;}printf("\n");/*insert a node whose value is b before a*/printf("Please input the position for a\n ch_a=");getchar();scanf("%c",&ch_a);getchar();printf("Please input the value that you want to insert\n ch_b=");scanf("%c",&ch_b);getchar();insert(&my_head,ch_a,ch_b);printf("The link list after insertion is like:\n");p=my_head;while (p != NULL){printf("%c ",p->data);p=p->next;}printf("\n");/*delete a node whose value is a*/printf("Please input the position for a a=");scanf("%c",&ch_a);getchar();deletenode(&my_head,ch_a);printf("The link list after deleting is like:\n");p=my_head;while (p != NULL){printf("%c ",p->data);p=p->next;}printf("\n");}实验二、栈和队列的应用程序1:顺序栈的实现和运算#include<stdio.h>#define MAXN 26char stack[MAXN];int top=0;int push(char x){if (top >= MAXN)return(1);stack[top++]=x;return(0);}int pop(char *p_y){if (top == 0)return(1);*p_y = stack[--top];return(0);}void main(){ int i;char ch_x,ch_y;printf("input the char you want to push\n");scanf("%c",&ch_x);while(ch_x!='0')if (push(ch_x)==1) printf("failure!\n");else{printf("success!\n");printf("input a char for ch_x to push\nch_x=");getchar();scanf("%c",&ch_x);}i=0;while(stack[i]!='\0'){printf("%c ", stack[i]);i++;}if (pop(&ch_y)==1) printf("failure!\n");else{printf("success!\n");printf("The pop char is %c\n",ch_y);} for (i=top-1; i>=0; i--)printf("%c ", stack[i]);}程序2:链栈的实现和运算#include <stdio.h>#include <malloc.h>struct node{char data;struct node *link;};typedef struct node NODE;NODE * top = NULL;void push_l(char x){NODE *p;p = (NODE * )malloc(sizeof(NODE));p->data = x;p->link = top;top = p;}int pop_l(char *p_y){NODE *p;if (top == NULL)return(1);* p_y = top->data;p = top;top = top->link;free(p);return(0);}void main(){ NODE *p;char ch_x,ch_y;printf("input the char you want to push\n");scanf("%c",&ch_x);while(ch_x!='0'){push_l(ch_x);getchar();scanf("%c",&ch_x);}p=(NODE*)malloc(sizeof(NODE));p=top;while(p!=NULL){printf("%c ",p->data);p=p->link;}printf("\n");if (pop_l(&ch_y)==1) printf("failure!\n");else{printf("success!\n");printf("The pop char is %c\n",ch_y);}p=(NODE*)malloc(sizeof(NODE));p=top;while(p!=NULL){printf("%c ",p->data);p=p->link;}printf("\n");}程序3:顺序队列的实现和运算#include<stdio.h>#define MAXN 26char q[MAXN];int head = -1, tail = -1;int en_queue(char x ){if (tail == MAXN-1)return(1);q[++tail] = x;return(0);}int de_queue(char *p_y ){if (head == tail)return(1);*p_y = q[++head];return(0);}void main(){ int i;char ch_x,ch_y;printf("input the char you want to enqueue\n");scanf("%c",&ch_x);while(ch_x!='0')if (en_queue(ch_x)==1) printf("failure!\n");else{printf("success!\n");printf("input a char for ch_x to enqueue\nch_x=");getchar();scanf("%c",&ch_x);}i=1;while(q[i]!='\0'){printf("%c ", q[i]);i++;}if (de_queue(&ch_y)==1) printf("failure!\n");else{printf("success!\n");printf("The dequeue char is %c\n",ch_y);}for (i=head+1; i<=tail; i++)printf("%c ", q[i]);}程序4:链式队列的实现和运算#include<stdio.h>#include<malloc.h>"struct node{char data;struct node * link;};typedef struct node NODE;NODE *head, *tail;void en_queue_l(char x){NODE *p;p = (NODE *)malloc(sizeof(NODE));p->data = x;p->link = NULL;if (head == NULL)head = p;elsetail->link = p;tail = p;}int de_queue_l(char *p_y){NODE *p;if (head == NULL)return(1);*p_y = head->data;p = head;head = head->link;free(p);return(0);}void main(){ NODE *p;char ch_x,ch_y;printf("input the char you want to enqueue\n");scanf("%c",&ch_x);while(ch_x!='0'){en_queue_l(ch_x);getchar();scanf("%c",&ch_x);}p=(NODE*)malloc(sizeof(NODE));p=head;while(p!=NULL){printf("%c ",p->data);p=p->link;}printf("\n");if (de_queue_l(&ch_y)==1) printf("failure!\n");else{printf("success!\n");printf("The dequeue char is %c\n",ch_y);} p=(NODE*)malloc(sizeof(NODE));p=head;while(p!=NULL){printf("%c ",p->data);p=p->link;}printf("\n");}程序5:循环队列的实现和运算#include<stdio.h>#include<string.h>#define MAXN 26char q[MAXN];int head = 0, tail = 0;int en_c_q(char x){tail = (tail + 1) % MAXN;if (tail == head){if (tail == 0) tail = MAXN-1;else tail--;return(1);}q[tail] = x;return(0);}int de_c_q(char *p_y){if (head == tail)return(1);head = (head+1) % MAXN;*p_y = q[head];return(0);}void main(){ int i;char ch_x,ch_y;printf("input the char you want to enqueue\n");scanf("%c",&ch_x);while(ch_x!='0')if (en_c_q(ch_x)==1) printf("failure!\n");else{printf("success!\n");printf("input a char for ch_x to enqueue\nch_x=");getchar();scanf("%c",&ch_x);}i=1;while(q[i]!='\0'){printf("%c ", q[i]);i++;}if (de_c_q(&ch_y)==1) printf("failure!\n");else{printf("success!\n");printf("The dequeue char is %c\n",ch_y);}for (i=head+1; i<=tail; i++)printf("%c ", q[i]);}实验三、多维数组和串程序1:稀疏矩阵的存储及转置运算#include <stdio.h>typedef struct {int row ;int col ;int val ;}THA ;#define MAX 20main( ){ int i, j, count=1 ;int col, row, val ;THA s[MAX];THA t[MAX];printf("input the number of row ,col and elements:"); scanf("%d,%d,%d",&s[0].row,&s[0].col,&s[0].val);if(s[0].val==0) return ;val =s[0].val;for(i=1;i<=val;i++);scanf("%d,%d,%d",&s[i].row,&s[i].col,&s[i].val);row = s[0].row ;col= s[0].col ;count=1 ;for( i=1; i<= col ; i++)for ( j=1; j<=val ; j++)if (s[j].col==i){t[count].row = s[j].col;t[count].col = s[j].row;t[count++].val = s[j].val;}t[0].row = col ;t[0].col = row ;t[0].val = val ;for(i=0;i<=val;i++)printf("%d,%d,%d\n",t[i].row,t[i].col,t[i].val); }程序2:串的实现和运算#include <stdio.h>#define MAXN 128typedef enum {fail,success} status;typedef enum {false,true} boolean;main(){ int strlen();void strass();boolean strcmp();status strcat( );status strins();void patmatch();int t,n,i;boolean b;status st;char s[MAXN],s1[MAXN],s2[MAXN];printf("\n1. The length of string\n");printf(" 2. The assignment of string\n");printf(" 3. A string compare with another string:\n");printf(" 4. A string connect with another string:\n");printf(" 5. A string to be inserted into another string\n"); printf(" 6. The pattern match of string :");printf(" Please input a opertation:");scanf("%d",&t);switch(t){ case 1:printf("please input a string:\n");getchar();gets(s);n=strlen(s);printf("the length is: %d",n);break;case 2:printf("please input the first string:\n");getchar();gets(s1);printf("please input the second string:\n");getchar();gets(s2);strass(s1,s2);break;case 3:printf("please input the first string:\n");getchar();gets(s1);printf("please input the second string: \n");gets(s2);b=strcmp(s1,s2);if (b==true)printf("equal\n");elseprintf("not equal\n");break;case 4:printf("please input the first string:\n");getchar();gets(s1);printf("please input the second string:\n");gets(s2);st=strcat(s1,s2);if(st==success)printf("answer is %s\n",s1);elseprintf("error!\n");break;case 5:printf("please input the first string:\n");getchar();gets(s1);printf("please input the second string:\n");gets(s2);printf("please input i:");scanf("%d",&i);st=strins(s1,i,s2);if(st==success)printf("answer is %s\n",s1);else printf("error!\n");break;case 6:patmatch();break;default: printf("There isn't this operation!"); }}int strlen(s)char s[];{ int i;for(i=0;s[i]!='\0';i++);return (i);}void strass(s1,s2)char s1[],s2[];{ int i=0;while(s1[i]!='\0'){ s2[i]=s1[i];i++;}s2[i]='\0';printf("s2 is %s",s2);}boolean strcmp(s1,s2)char s1[],s2[];{ int i=0;while (s1[i]==s2[i] && s1[i]!='\0' && s2[i]!='\0') i++;if (s1[i]=='\0' && s2[i]=='\0')return (true);elsereturn (false);}status strcat (s1,s2)char s1[],s2[];{ int i,j,k;i=strlen(s1);j=strlen(s2);if((i+j)>=MAXN)return(fail);for(k=0;k<=j;k++)s1[i+k]=s2[k];return (success);}status strins (s1,i,s2)char s1[],s2[];int i;{ int m,n,k;m=strlen(s1);n=strlen(s2);if (i<0||i>m||(m+n)>MAXN )return (fail) ;for(k=m;k>=i;k--)s1[k+n]=s1[k];for(k=0;k<n;k++)s1[i+k]=s2[k];return (success);}int smatch(ch,n,pat,m)char ch[],pat[];int n,m;{ int s,p,k;for(s=0;s<=n-m;s++){for(p=0,k=s;p<m&&ch[k]==pat[p];k++,p++);if(p==m)return(s+1);}return(-1);}void patmatch(){ char ch[MAXN],pat[MAXN];int n,m, result;printf("\ninput the primary string:\n");scanf("%s",ch);printf("input the pattern string:\n");scanf("%s",pat);n=strlen(ch);m=strlen(pat);result=smatch(ch,n,pat,m);if(result==-1)printf("\nNo matched found!");else if(result>=0) printf("\nMatched sub string found in position %d",result); }实验四、树和二叉树的操作程序1:二叉树的实现和运算#include <stdio.h>#include <stdlib.h>#include <malloc.h>typedef struct btnode{char data; /*suppose the data field's type is char*/struct btnode *lchild; /*left pointer field */struct btnode *rchild; /*right pointer field */}NODE;void main(){ NODE *root,*q,n;NODE *create(NODE *p);void preorder(NODE *root);void inorder(NODE *root);void postorder(NODE *root);int t;q=&n;root=create(q);printf("At the first,we create a tree\n");printf("Please input nodes of tree\n");if (root==NULL) printf("It's an empty tree!\n");else{printf("\n1.The preordetraverse \n");printf(" 2.The inordertraverse \n");printf(" 3.The postordertraverse \n");printf(" Please choose a kind of order\n");scanf("%d",&t);switch (t){case 1: preorder(root); break;case 2: inorder(root); break;case 3:postorder(root); break;default: printf(" The error!");}}}NODE * create(NODE *p) /*create the structure of binary tree */ { char ch;NODE *t;scanf("%c",&ch);if(ch==' ') p=NULL;else{p->data=ch;t=(NODE *)malloc(sizeof(NODE));p->lchild=create(t);t=(NODE*)malloc(sizeof(NODE));p->rchild=create(t);}return p;}void preorder(NODE *root) /*travel the tree using preorder */ { if (root!=NULL){ printf( " %c", root->data);preorder(root->lchild);preorder(root->rchild);}return;}void inorder (NODE *root) /*travel the tree using inorder */ { if (root!=NULL){ inorder(root->lchild);printf(" %c ", root->data);inorder(root->rchild);}return;}void postorder(NODE *root) /*travel the tree using postorder */{ if (root!=NULL){ postorder (root->lchild);postorder (root->rchild);printf(" %c ", root->data);}return;}程序2:线索二叉树的实现和运算#include <stdio.h>#include <stdlib.h>#include <malloc.h>struct btnode{ char data; /*data field*/int lbit; /*left flag field*/int rbit; /*right flag field*/struct btnode *lchild; /*left pointer field */struct btnode *rchild; /*right pointer fieldò**/ };typedef struct btnode NODE;NODE *pre;void main(){ NODE * create(NODE *p );void inthread(NODE *root );NODE *q,*root ;q=(NODE *)malloc(sizeof(NODE));printf("\nAt first,we create a tree!\n" );printf("Please input the data of the tree!\n" );root=create(q);inthread(root);}NODE * create(NODE *p) /*create a structure of binary tree */ { char ch;NODE *t; /*suppose the type of the data is int */scanf("%c",&ch);if(ch==' ')p=NULL;else{ p->data=ch;p->lbit=0;t=(NODE *)malloc(sizeof(NODE));p->lchild=create(t);t=(NODE*)malloc(sizeof(NODE));p->rchild=create(t);}return p;}void inthread(NODE *root ){void inthreading(NODE **p);void invodth(NODE **h);NODE *t;t=((NODE *)malloc(sizeof(NODE)));t->lbit=0; t->rbit=1;t->rchild=t;if (root==NULL)t->lchild=t;else{ pre=t;inthreading(&root); /*produce the thread tree using inorder */t->lchild=root; /* the last node form the thread */pre->rchild=t;pre->rbit=1;t->rchild=pre;}invodth(&t);}void inthreading(NODE **p){ if ((*p)!=NULL){inthreading(&((*p)->lchild)); /*left subtree form the thread */if(((*p)->lchild)==NULL){ (*p)->lbit=1;(*p)->lchild=pre;}if (pre->rchild==NULL){ pre->rbit=1;pre->rchild=*p;}pre=*p;inthreading(&((*p)->rchild));/*right subtree form the thread*/}}void invodth(NODE **h) /*travel the binary tree using the inorder thread */ { NODE *p;p=(*h)->lchild;while(p!=(*h)){ while (p->lbit==0)p=p->lchild;if (p->lbit==1)printf(" %c",p->data);while ( p->rbit==1 && p->rchild!=(*h)){ p=p->rchild;printf(" %c",p->data);}p=p->rchild;}}程序3:哈夫曼树的实现和运算#include<stdio.h>#include <stdlib.h>#include <malloc.h>#define m 100struct ptree /* define the type of binary tree*/ { int w;struct ptree * lchild;struct ptree * rchild;};struct pforest /*define the type of chain belt*/{ struct pforest *link;struct ptree *root;};int WTL=0;void main(){ struct ptree *hafm(int w[m],int n );void travel(struct ptree *head,int n );struct ptree *head;int n,i,w[m];printf("please input the sum of node\n");scanf("%d",&n);printf("please input weight of every node\n");for(i=1;i<=n;i++)scanf("%d",&w[i]);head=hafm(w,n);travel(head,0);printf("The length of the best path is WTL=%d",WTL); }void travel(struct ptree *head,int n){ struct ptree *p;p=head;if (p!=NULL){ if((p->lchild)==NULL&&(p->rchild)==NULL){ printf(" %d",p->w);printf(" the hops of the node is: %d\n",n);WTL=WTL+n*(p->w);}travel(p->lchild,n+1);travel(p->rchild,n+1);}}struct ptree *hafm(int w[m],int n){ struct pforest *inforest(struct pforest *f, struct ptree *t ); struct pforest *p1,*p2,*f;struct ptree *ti,*t,*t1,*t2;int i;f=(struct pforest*)malloc(sizeof(struct pforest));f->link=NULL;for (i=1;i<=n;i++) /*produce n trees that have only rootnode*/ {ti=(struct ptree *)malloc(sizeof(struct ptree));ti->w=w[i];ti->lchild=NULL;ti->rchild=NULL;f=inforest (f,ti);}while(((f->link)->link)!=NULL) /* at least have two binary trees*/ { p1=f->link;p2=p1->link;f->link=p2->link; /*take out frontal two trees*/t1=p1->root;t2=p2->root;free(p1);free(p2);t=(struct ptree *)malloc (sizeof(struct ptree));t->w=t1->w+t2->w; /*weight be added */t->lchild=t1;t->rchild=t2; /*produce the new binary tree */f=inforest(f,t);}p1=f->link;t=p1->root;return(t);}struct pforest * inforest(struct pforest *f, struct ptree *t) { struct pforest *p, *q, *r;struct ptree *ti;r=(struct pforest *) malloc(sizeof(struct pforest));r->root=t;q=f;p=f->link;while (p!=NULL) /*look for the position to be inserted*/ { ti=p->root;if( t->w>ti->w ){ q=p;p=p->link;}elsep=NULL; /*force exit the cycle*/}r->link=q->link;q->link=r;return (f);}实验五、图的操作程序1:图的实现和运算#include <stdio.h>#include <stdlib.h>#include <alloc.h>struct node{ int vertex;struct node *next;};struct headnode{ int vert;struct node *link;};main(){ int t,n,i,visit[100];int d[100];struct headnode *adjlist( );void dfs( );void wfs( );struct headnode *head ;printf("input the sum of nodes:\n");scanf("%d",&n);for(i=0;i<n;i++)scanf("%d",&d[i]);head=adjlist(d,n);printf("1 depth travel\n");printf("2 width travel\n");printf("please input the way of travelling\n");scanf("%d",&t);switch (t){ case 1:for(i=0;i<n;i++)visit[i]=0;dfs(head,1,visit);break;case 2:wfs(head,n);break;default:printf("The error!");}}struct headnode *adjlist(d,n)int n;int d[ ];{ struct headnode head[100] ;struct node *q,*p ;int i,v1;for(i=0; i<n;i++){ head[i].vert=d[i];head[i].link=NULL;printf("input linked list of\n");scanf("%d ",&v1);while(v1>=0){ p=(struct node *) malloc(sizeof(struct node));p->vertex=v1;p->next=head[i].link ;head[i].link=p;scanf("%d", &v1);}}return(head);}void dfs(head,k,visit)struct headnode head[1000];int k,visit [ ];{int i;struct node *p;printf(" v%d",k);visit[k]=1;p=head[k-1].link;while ( p!=NULL){if (visit[p->vertex]==0)dfs(head,p->vertex,visit);p=p->next;};return;}void wfs(head,n)struct headnode *head;int n;{int visit[1000],q[1000],f,r,k,u,m; struct node *p;for(k=0;k<n;k++)visit[k]=0;f=0;r=0;m=0;if (visit[m]==0)q[r]=(head+m)->vert;r=r+1;visit[m]=1;while (f!=r){ u=q[f];f=f+1;printf(" v%d",u);p=(head+u-1)->link;while (p!=NULL){ if (visit[p->vertex-1]==0){ q[r]=p->vertex;r=r+1;visit[p->vertex-1]=1;}p=p->next;}}}程序2:最小生成树#define M 30#define MAX 99#include <stdio.h>#include <stdlib.h>main(){void prim();int i,j,n,g[100][100];printf("input the sum of nodes:\n");scanf("%d",&n);printf("input the content of adjtrix:\n");for (i=1;i<=n;i++)for(j=1;j<=n;j++)scanf("%d",&g[i][j]);prim(g,1,n);}void prim(g,k,n)int g[100][100];int k,n;{int i,j,min,p;struct { int adjvex;int lowcost;}closedge[M];for(i=1;i<=n;i++)if(i!=k){closedge[i].adjvex=k;closedge[i].lowcost=g[k][i];}closedge[k].lowcost=0;for(i=1;i<=n;i++){p=1;min=MAX;for(j=1;j<=n;j++)if(closedge[j].lowcost!=0 && closedge[j].lowcost<min) {min=closedge[j].lowcost;p=j;}if (min!=MAX)printf("%d---%d %d\n",closedge[p].adjvex,p,min); closedge[p].lowcost=0;for(j=1;j<=n;j++)if (g[p][j]<closedge[j].lowcost){ closedge[j].lowcost=g[p][j];closedge[j].adjvex=p;}}}程序3:最短路径#define M 30#define MAX 99#include <stdio.h>#include <stdlib.h>main(){ void prim();int i,j,n,g[100][100];printf("input the sum of nodes:\n");scanf("%d",&n);printf("input the content of adjtrix:\n");for (i=1;i<=n;i++)for(j=1;j<=n;j++)scanf("%d",&g[i][j]);prim(g,1,n);}void prim(g,k,n)int g[100][100];int k,n;{int i,j,min,p;struct {int adjvex;int lowcost;}closedge[M];for(i=1;i<=n;i++)if(i!=k){ closedge[i].adjvex=k;closedge[i].lowcost=g[k][i];}closedge[k].lowcost=0;for(i=1;i<=n;i++){p=1;min=MAX;for(j=1;j<=n;j++)if(closedge[j].lowcost!=0 && closedge[j].lowcost<min) {min=closedge[j].lowcost;p=j;}if (min!=MAX)printf("%d---%d %d\n",closedge[p].adjvex,p,min); closedge[p].lowcost=0;for(j=1;j<=n;j++)if (g[p][j]<closedge[j].lowcost){ closedge[j].lowcost=g[p][j];closedge[j].adjvex=p;}}}程序4:每一对顶点之间的最短路径(Floyd方法)#define M 100#include <stdio.h>#include <stdlib.h>main(){ void floyd( );int i,j,n,ad[M][M],p[M][M];printf("input the sum of nodes\n"); scanf("%d",&n);for(i=0;i<n;i++)for(j=0;j<n;j++)scanf("%d",&ad[i][j]);floyd(ad,p,n);for(i=0;i<n;i++){ for(j=0;j<n;j++)printf(" %d ",p[i][j]);printf("\n");}}void floyd(ad,p,n )int ad[ ][M],p[][M],n;{int i,j,k;for(i=0;i<n;i++)for(j=0;j<n;j++){ if(i==j)p[i][j]=0;elseif (ad[i][j]<M)p[i][j]=i+1;else p[i][j]=0;}for(k=0;k<n;k++)for(i=0;i<n;i++)for(j=0;j<n;j++)if(ad[i][k]+ad[k][j]<ad[i][j]) { ad[i][j]=ad[i][k]+ad[k][j];p[i][j]=p[k][j];}}程序5;拓扑排序#define M 100#include<stdio.h>#include<stdlib.h>#include <alloc.h>struct node{ int vertex ;struct node *next ;。

数据结构与算法实验源代码

数据结构与算法实验源代码

数据结构与算法实验源代码数据结构与算法实验源代码一、实验目的本实验旨在通过编写数据结构与算法的实验源代码,加深对数据结构与算法的理解,并提高编程能力。

二、实验环境本实验使用以下环境进行开发和测试:- 操作系统:Windows 10- 开发工具:IDEA(集成开发环境)- 编程语言:Java三、实验内容本实验包括以下章节:3.1 链表在本章节中,我们将实现链表数据结构,并实现基本的链表操作,包括插入节点、删除节点、查找节点等。

3.2 栈和队列在本章节中,我们将实现栈和队列数据结构,并实现栈和队列的基本操作,包括入栈、出栈、入队、出队等。

3.3 树在本章节中,我们将实现二叉树数据结构,并实现二叉树的基本操作,包括遍历树、搜索节点等。

3.4 图在本章节中,我们将实现图数据结构,并实现图的基本操作,包括广度优先搜索、深度优先搜索等。

3.5 排序算法在本章节中,我们将实现各种排序算法,包括冒泡排序、插入排序、选择排序、快速排序、归并排序等。

3.6 搜索算法在本章节中,我们将实现各种搜索算法,包括线性搜索、二分搜索、广度优先搜索、深度优先搜索等。

四、附件本文档附带实验源代码,包括实现数据结构和算法的Java源文件。

五、法律名词及注释5.1 数据结构(Data Structure):是指数据对象中数据元素之间的关系。

包括线性结构、树形结构、图形结构等。

5.2 算法(Algorithm):是指解决问题的一系列步骤或操作。

算法应满足正确性、可读性、健壮性、高效性等特点。

5.3 链表(Linked List):是一种常见的数据结构,由一系列节点组成,每个节点包含一个数据元素和一个指向下一个节点的指针。

5.4 栈(Stack):是一种遵循后进先出(LIFO)原则的有序集合,用于存储和获取数据。

5.5 队列(Queue):是一种遵循先进先出(FIFO)原则的有序集合,用于存储和获取数据。

5.6 树(Tree):是由节点组成的层级结构,其中一种节点作为根节点,其他节点按照父子关系连接。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验一线性表的链式存储结构一、实验目的:1.掌握线性表的链式存储结构。

2.熟练地利用链式存储结构实现线性表的基本操作。

3.能熟练地掌握链式存储结构中算法的实现。

二、实验内容:1.用头插法或尾插法建立带头结点的单链表。

2.实现单链表上的插入、删除、查找、修改、计数、输出等基本操作。

三、实验要求:1. 根据实验内容编写程序,上机调试、得出正确的运行程序。

2. 写出实验报告(包括源程序和运行结果)。

四、实验学时:2学时五、实验步骤:1.进入编程环境,建立一新文件;2. 参考以下相关内容,编写程序,观察并分析输出结果。

①定义单链表的数据类型,然后将头插法和尾插法、插入、删除、查找、修改、计数、输出等基本操作都定义成子函数的形式,最后在主函数中调用它,并将每一种操作前后的结果输出,以查看每一种操作的效果。

②部分参考程序//单链表的建立(头插法),插入,删除,查找、修改、计数、输出#include<iostream.h>#define elemtype intstruct link{ elemtype data;//元素类型link *next;//指针类型,存放下一个元素地址};//头插法建立带头结点的单链表link *hcreat(){ link s,p;elemtype i;cout<<”输入多个结点数值(用空格分隔),为0时算法结束”;cin>>i;p=new link;p->next=NULL;while(i) //当输入的数据不为0时,循环建单链表{s=new link;s->data=i;s->next=p->next;p->next=s;cin>>i;}return p;}//输出单链表void print(1ink *head){1ink *p;p=head->next;while(p->next!=NULL){cout<<p->data<<”->”;//输出表中非最后一个元素p=p->next;}cout<<p->data;//输出表中最后一个元素cout<<endl;}∥在单链表head中查找值为x的结点Link *Locate(1ink *head,elemtype x){Link *p;p=head->next;while((p!=NULL)&&(p->data!=x))p=p->next;return p;}//在head为头指针的单链表中,删除值为x的结点void deletel(1ink *head,elemtype x){1ink *p,*q;q=head;p=head->next;while((p!=NULL)&&(p->data!=x)){q=p;p=p->next;}If(p==NULL) cout<<“要删除的结点不存在”;elseq->next=p ->next;}}//在头指针head所指的单链表中,在值为x的结点之后插入值为y的结点void insert(1ink *head,elemtype x,elemtype y){link *p,*s;s=new link;s->data=y;if(head->next==NULL) //链表为空{head->next=s;s->next=NULL:}p=Locate(head,x);//调用查找算法‘if(p==NULL)cout<<”插入位置非法”:else(s->next=p->next;p->next=s;}}//将单链表p中所有值为x的元素修改成yvoid change(1ink *p,elemtype x,elemtype y){link *q;q=p->next;while(q!=NULL){ if(q->data==x) q->data=y;q=q->next;}}void count(1ink *h) //统计单链表中结点个数{1ink *p;int n=0;p=h->next;while(p!=NULL){n++;p=p->next;}return n;}void main()elemtype x,y;link *p,*q;p=hcreat();//头插法建立链表print(p);//输出刚建立的单链表cout<<”请输入要删除的元素”;cin>>y;deletel(p,y);print(p);//输出删除后的结果cout<<”请输入插入位置的元素值(将待插元素插入到它的后面)”;cin>>x;cout<<”请输入待插元素值”;cin>>y;insert(p,x,y);print(p);//输出插入后的结果cout<<”请输入要修改前、后的元素值”;cin>>x>>y;change(p,x,y);print(p);cout<<”请输入要查找的元素值”;cin>>x;q=Locate(p,x);if(q==NULL)cout<<x<<”不在表中,找不到!”<<endl;else cout<<x<<”在表中,已找到!”<<endl;n=count(p);cout<<”链表中结点个数为:”<<n<<endl:}//单链表的建立(尾插法)、插入、删除、查找、修改、计数、输出#include<iostream.h>#define elemtype intstruct link{ elemtype data;//元素类型link *next;//指针类型,存放下-个元素地址};//尾插法建立带头结点的单链表link *rcreat(){link *s,*p,*r;elemtype i;cout<<”输入多个结点数值(用空格分隔),为0时算法结束”;p=r=new link;p->next=NULL;while(i){s=new link;s->data=i;r->next=s;r=s;cin>>i;}r->next=NULL;return p;}//输出单链表void print(1ink *head){link *p;p=head->next;while(p->next!=NULL){cout<<p->data<<"->”; //输出表中非最后一个元素p=p->next;)cout<<p->data;//输出表中最后一个元素cout<<endl;}link *Locate(1ink *head,int x) ∥在单链表中查找第x个结点{link *p;p=head;int j=0;while((p!=NULL)&&(j<x)){p=p->next; j++;}return p;}void delete I(1ink *head,elemtype x)//在head为头指针的单链表中,删除值为x的结点{link *p, *q;q=head;p=head->next;while((p!=NULL)&&(p->data!=x)){q=p;p=p->next;)if(p==NULL)cout<<”要删除的结点不存在“;else{q->next=p->next;delete(p);} }void insert(1ink *head,int x,elemtype y)//在头指针head所指单链表中,在第x个结点之后插入值为y的结点{link *p,*s;s=new link;s->data=y;if(head->next==NULL)//链表为空{head->next=s;s->next=NULL:}p=Locate(head,x);//调用查找算法if(p==NULL)cout<<”插入位置非法”;else{s->next=p->next;p->next=s;}}void change(1ink *p,elemtype x,elemtype y){∥将单链表P中所有值为x的元素改成值为ylink *q;q=p->next;while(q!=NULL){if(q->data==x)q->data=y;q=q->next;}}void count(1ink *h) //统计单链表中结点个数(1ink *p;int n=0;p=h->next;while(p!=NULL){n++;p=p->next;}retum n;}void main(){ int n;link p,q;p=rcreat();//尾插法建立链表print(p);//输出刚建立的单链表cout<<”请输入要删除的元素”;cin>>y;deletel(p,y);print(p);//输出删除后的结果cout<<”请输入插入位置”;cin>>x;cout<<”请输入待插元素值”;cin>>y;insert(p,x,y);print(p);//输出插入后的结果cout<<”请输入修改前、后的元素值”;cin>>x>>y;change(p,x,y);print(p);cout<<“请输入要查找的元素值”;cin>>x;q=Locate(p ,x);if(q==NULL)cout<<x<<”不在表中,找不到!”<<endl;else cout<<x<<”在表中,已找到!”<<endl;n=count(p);cout<<”链表中结点个数为:”<<n<endl;}六、选作实验试设计一元多项式相加(链式存储)的加法运算。

A(X)=7+3X+9X8+5X9B(X)=8X+22X7-9X81.建立一元多项式;2.输出相应的一元多项式;3.相加操作的实现。

相关文档
最新文档