数据结构——单链表
来源:互联网 发布:oracle数据库网速 编辑:程序博客网 时间:2024/06/08 18:59
问题及代码
编写一个程序exp2-2.cpp,实现单链表的各种基本运算(假设单链表的元素类型为char),并在此基础上完成如下功能:
(1)初始化单链表h;
(2)采用尾插法依次插入元素a,b,c,d,e;
(3)输出单链表h;
(4)输出单链表h长度;
(5)判断单链表h是否为空;
(6)输出单链表h的第3个元素;
(7)输出元素a的位置;
(8)在第4个元素位置上插入元素f;
(9)输出单链表h;
(10)删除h的第3个元素;
(11)输出单链表h;
(12)释放单链表h。
代码#include <iostream>#include<stdio.h>#include<malloc.h>#define SizeMax 50using namespace std;typedef char ElemType;typedef struct Node{ ElemType data; struct Node *next;} SqList;void InitList(SqList *&h){ printf("(1)初始化单链表h\n"); h=(SqList *)malloc(sizeof(SqList)); h->next=NULL;}void Insert(SqList *&h,char x){ SqList *s,*p; p=h; while(p->next!=NULL) p=p->next; s=p; p=(SqList *)malloc(sizeof(SqList)); p->data=x; s->next=p; p->next=NULL;}void Print(SqList *&h){ SqList *p=h->next; while(p!=NULL) { printf("%c ",p->data); p=p->next; } printf("\n");}void PrintLength(SqList *&h){ int n=0; SqList *p=h; while(p->next!=NULL) { n++; p=p->next; } printf("%d\n",n);}bool SqNull(SqList *&h){ if(h->next==NULL) return false; else return true;}bool PrintData(SqList *&h,int i){ int j=0; SqList *p=h; while(j<i&&p!=NULL) { j++; p=p->next; } if(p==NULL) return false; else { printf("%c\n",p->data); return true; }}bool Find(SqList *&h,char x){ int i=1; SqList *p=h->next; while(p!=NULL&&p->data!=x) { p=p->next; i++; } if(p==NULL) return 0; else return i;}bool Insertinto(SqList *&h,int i,ElemType f){ int j=0; SqList *s,*p=h; i--; while(j<i&&p!=NULL) { j++; p=p->next; } if(p==NULL) return false; else { s=(SqList *)malloc(sizeof(SqList)); s->data=f; s->next=p->next; p->next=s; return true; }}bool Delete(SqList *&h,int i){ int j=0; SqList *q,*p=h; while(j<i-1&&p!=NULL) { j++; p=p->next; } if(p==NULL) return false; else { q=p->next; if(q==NULL) return false; p->next=q->next; free(q); return true; }}int main(){ SqList *h; InitList(h); //初始化单链表 ElemType a,b,c,d,e; printf("(2)依次采用尾插法插入a,b,c,d,e元素:"); scanf("%c %c %c %c %c%*c",&a,&b,&c,&d,&e); Insert(h,a); Insert(h,b); Insert(h,c); Insert(h,d); Insert(h,e); printf("(3)输出单链表h:") ; Print(h); printf("(4)单链表h长度:") ; PrintLength(h); if(SqNull(h)) printf("(5)单链表h为非空\n"); else printf("(5)单链表h为空\n"); printf("(6)单链表h的第三个元素="); PrintData(h,3); printf("(7)元素a的位置:%d\n",Find(h,a)); ElemType f; printf("(8)在第4个元素位置上插入f元素:"); scanf("%c",&f); Insertinto(h,4,f); printf("(9)输出单链表h:") ; Print(h); printf("(10)删除h的第三个元素\n") ; Delete(h,3); printf("(11)输出单链表h:") ; Print(h); printf("(12)释放单链表h:") ; free(h); return 0;}运算结果
阅读全文
0 0
- 数据结构——单链表
- 数据结构——单链表
- 数据结构——单链表
- 数据结构——单链表
- 数据结构——单链表
- 数据结构——单链表
- 数据结构——单链表
- 数据结构——单链表
- 数据结构——单链表
- 数据结构——单链表
- 数据结构——单链表
- 数据结构——单链表
- 数据结构——单链表
- 数据结构——单链表
- 数据结构—单链表瞎搞
- 数据结构—单链表
- 【数据结构】单链表—逆置单链表
- 数据结构—单链表
- 文件夹恶意软件WORM_AUTORUN.FIU处理
- 认识ViewGroup
- python中一些常用的函数命令
- java中调用R
- 关于获取安卓手机系统输入法和设置输入法
- 数据结构——单链表
- tpwr886n 管理员密码忘了,怎么进行出厂设置?
- centos 7+hadoop 2.7.3
- 完美解决gradle下载慢的问题
- IOS版本检测,更新版本
- 什么是CPS、CPA、CPC、CPM?
- Windows下C++多线程同步与互斥简单运用
- 微服务框架Finagle介绍 Part1: Future, Service, Filter
- 泛型