2007-01-04
数据结构课程源代码之单链表实现
关键字: 数据结构 源代码 单链表
/*
SingleLinkList.h 定义单链表结构及基本操作
*/
/*
SingleLinkList.cpp 测试文件
*/
SingleLinkList.h 定义单链表结构及基本操作
*/
cpp 代码
- #define OK 1
- #define ERROR 0
- #define TRUE 1
- #define FALSE 0
- #define OVERFLOW -2
- typedef int Status;
- typedef int ElemType;
- typedef struct LNode {
- ElemType data;
- struct LNode *next;
- } LNode,*LinkList;
- /*
- 单链表初始化操作,带头结点(头结点不存储数据,统一操作)
- */
- Status InitList_SL(LinkList& l) {
- l=(LNode*)malloc(sizeof(LNode));
- l->next=NULL;
- return OK;
- }
- /*
- 单链表销毁操作
- */
- Status DestoryList_SL(LinkList& l) {
- LNode *q,*p=l;
- while(p) {
- q=p->next;
- free(p);
- p=q;
- }
- l=NULL;
- return OK;
- }
- /*
- 单链表头插法
- */
- Status CreateList_SL(LinkList& l,int n) {
- LNode* p;
- printf("请输入 %d 个数构造单链表:\n",n);
- for(int i=1;i<=n;i++) {
- p=(LNode*)malloc(sizeof(LNode));
- scanf("%d",&p->data);
- p->next=l->next;
- l->next=p;
- }
- return OK;
- }
- /*
- 取出第 i 号位元素,用 e 带回
- */
- Status GetElem(LinkList l,int i,ElemType& e) {
- LNode* p=l->next;
- int j=1;
- while(p&&j
- p=p->next;
- ++j;
- }
- if(!p||ireturn ERROR;
- e=p->data;
- return OK;
- }
- /*
- 单链表的插入操作,插入元素 e 在第 i 号位
- */
- Status ListInsert_SL(LinkList& l,int i,ElemType e) {
- //带头结点的SingleList
- LNode* p=l;
- LNode* s;
- int j=0;
- while(p&&j
- p=p->next;
- ++j;
- }
- if(!p||i-1
- return ERROR;
- s=(LNode*) malloc (sizeof(LNode));
- s->data=e;
- s->next=p->next; //do insert
- p->next=s;
- return OK;
- }
- /*
- 单链表的删除操作, 删除第 i 个元素,保存在 e 中并带回
- */
- Status ListDelete_SL(LinkList& l,int i,ElemType& e) {
- LNode* p=l;
- LNode* q;
- int j=0;
- while(p->next&&j
- p=p->next;
- ++j;
- }
- if(!p->next||i-1
- return ERROR;
- }
- q=p->next;
- p->next=q->next;
- free(q);
- return OK;
- }
- /*
- 打印单链表 L 中的元素值
- */
- Status DisplayList_SL(LinkList& l) {
- LNode* p=l->next;
- printf("the SingleList is : ");
- while(p) {
- printf("%d ",p->data);
- p=p->next;
- }
- printf("\n");
- return OK;
- }
/*
SingleLinkList.cpp 测试文件
*/
cpp 代码
- #include "stdio.h"
- #include "stdlib.h"
- #include "SingleLinkList.h"
- /*
- 测试链表中各操作
- */
- int main() {
- LinkList a;
- ElemType e;
- //初始化
- InitList_SL(a);
- //测试头插法,建立链表
- CreateList_SL(a, 3);
- DisplayList_SL(a);
- GetElem(a,2,e);
- printf("从链表中取出的第2个元素为 %d\n", e);
- ElemType elem = 332;
- ListDelete_SL(a,3,e);
- printf("删除链表3号位元素后链表内容为:");
- DisplayList_SL(a);
- ListInsert_SL(a,2,elem);
- printf("在链表2号位插入 %d 后,链表内容为:",elem);
- DisplayList_SL(a);
- printf("\n");
- return 0;
- }
发表评论
- 浏览: 22766 次
- 性别:


- 详细资料
搜索本博客
我的相册
STA42447
共 60 张
共 60 张
最新评论
-
帝国梦醒,是时候收兵了! ...
一般后期,保持20个兵营,20个马厩,20个靶场 打电脑就没必要了,一队精兵加冲 ...
-- by shakesmin -
帝国梦醒,是时候收兵了! ...
帝国就是太累了,,,, 没规模,看着不爽。。。。。。
-- by icefire -
帝国梦醒,是时候收兵了! ...
大学时候班上许多人喜欢玩帝国。 我也是喜欢看别人玩。
-- by dengyin2000 -
帝国梦醒,是时候收兵了! ...
不错,顶一个,我爱看别人玩帝国,自己打不行,太累了
-- by zingers -
计算机理论基础--------进 ...
倒这也可以贴过来?请看看版规再发贴....
-- by 抛出异常的爱






评论排行榜