算法基础之链表

来源:互联网 发布:新东方软件 编辑:程序博客网 时间:2024/05/22 06:57

一、 抽象数据类型(ADT

ADT是一些操作的集合,不涉及如何实现操作的集合,可以看作是模块化设计的扩充。

这些操作的实现只在程序中编写一次,而程序中任何其他部分需要在该ADT上运行其中的一种操作时可以通过调用适当的函数来进行

 

二、链表的一些操作

1.测试链表是否为空链表

int Isempty(List l){    return l->next=NULL;}


2.测试当前位置是否是链表的末尾函数

int Islast(Position p,List l){     return p->next=NULL;}


3.查找元素所在位置

Position Find(ElementType x,List l){      Position p;      p=l->next;      while(p!=NULL && p->element!=x)             p=p->next;       return p;}


4.删除元素

void Delete(ElementType x,List l){      Position p,temp;      p=FindPrevious(x,l);      if(!IsLast(p,l))     {          temp=p->next;          p->next=temp->next;          free(temp);     }}Position FindPrevios(ElementType x,List l){ //找到对应元素的前驱      Position p=l;      while(p->next!=NULL && p->next->element!=x)      {              p=p->next;      }       return p;}


5.插入

void Insert(ElementType x,List l,Position p){       Position temp;       temp=(Position)malloc(sizeof(Position));       if(temp == NULL)       FatalError(“out of space!! ”);       temp->element=x;       if(p->next!=NULL)      {            temp->next=p->next;            p->next=temp;      }      else     {           p->next=temp;           temp->next=NULL;     }}


6.删除链表(利用临时指针存储下一个元素,防止释放当前元素后找不到下一个元素)

void DelectList(List l){      Position p,temp;      p=l->next;while(p!=NULL){      temp=p->next;      free(p);      p=temp;}


0 0
原创粉丝点击