单链表各种基本运算的算法

来源:互联网 发布:排课表的软件 编辑:程序博客网 时间:2024/05/18 06:27

【代码】//文件名:linklist.cpp

#include <stdio.h>#include <malloc.h>typedef int ElemType;typedef struct LNode{ElemType data;struct LNode *next;} LinkNode;void InitList(LinkNode *&L)     //初始化线性表{L=(LinkNode *)malloc(sizeof(LinkNode));L->next=NULL;}void DestroyList(LinkNode *L)   //销毁线性表{LinkNode *pre=L,*p=pre->next;while(p!=NULL){free(pre);pre=p;p=p->next;}free(pre);}void CreateListF(LinkNode *L,ElemType a[],int n)   //头插法建立链表{LinkNode *s;for(int i=0; i<n; i++){s=(LinkNode *)malloc(sizeof(LinkNode));s->data=a[i];s->next=L->next;L->next=s;}}void CreateListR(LinkNode *L,ElemType a[],int n)   //尾插法建立链表{LinkNode *s,*r;r=L;for(int i=0; i<n; i++){s=(LinkNode *)malloc(sizeof(LinkNode));s->data=a[i];r->next=s;r=s;}r->next=NULL;}bool ListEmpty(LinkNode *L)    //判断线性表是否为空表{return L->next==NULL;}int ListLength(LinkNode *L)    //求线性表的长度{int i=0;LinkNode *p=L;while(p->next!=NULL){i++;p=p->next;}return i;}void DispList(LinkNode *L)    //输出线性表{LinkNode *p=L->next;while(p!=NULL){printf("%d ",p->data);p=p->next;}printf("\n");}bool GetElem(LinkNode *L,int i,ElemType &e)  //求线性表中第i个元素值{int j=0;LinkNode *p=L;if(i<=0) return false;while(j<i&&p!=NULL){j++;p=p->next;}if(p==NULL)return false;else{e=p->data;return true;}}int LocateElem(LinkNode *L,ElemType e)  //查找第一个值为e的元素序号{int i=1;LinkNode *p=L->next;while(p!=NULL&&p->data!=e){p=p->next;i++;}if(p==NULL)return 0;elsereturn i;}bool ListInsert(LinkNode *L,int i,ElemType e)  //插入到第i个元素{int j=0;LinkNode *p=L,*s;if(i<=0) return false;while(j<i-1&&p!=NULL){j++;p=p->next;}if(p==NULL)return false;else{s=(LinkNode *)malloc(sizeof(LinkNode));s->data=e;s->next=p->next;p->next=s;return true;}}bool ListDelete(LinkNode *L,int i,ElemType &e)  //删除第i个元素{int j=0;LinkNode *p=L,*q;if(i<=0) return false;while(j<i-1&&p!=NULL){j++;p=p->next;}if(p==NULL)return false;else{q=p->next;if(q==NULL)return false;e=q->data;p->next=q->next;free(q);return true;}}






原创粉丝点击