数据结构——线性表中的算法

来源:互联网 发布:福建安全网络知识竞赛 编辑:程序博客网 时间:2024/05/01 18:38

循环右移算法:

把数组A看作数组ab,要得到数组ba,可以先将a,b分别转置得到数组B=a(-1)b(-1),再将B转制得到B(-1)=ba;

void Reverse(char A,int from,int to){for(int i=0;i<(to-from+1)/2;i++){char t;t=A[from+i];A[from+i]=A[to-i];A[to-i]=t;} } void Converse(char A[],int n,int k){Reverse(A,0,k-1);Reverse(A,k,n-1);Reverse(A,0,n-1);}

删除所有元素值为x的元素(要求空间复杂度为o(1)):

从头开始遍历,用一个变量k来记录已经扫描到的值为x元素的个数,当扫描到的元素值不为x时,将此元素向前移动k位,当扫描到值为x的元素时,k++。

void deleteAllx(Seqlist L,int x){k=0;for(int i=0;i<L.length;i++){if(L.data[i]==x) k++;else L.data[i-k]=L.data[i];}L.length=L.length-k;}

实现单链表就地逆置:

1.通过修改指针实现

void reserve2(Node *first)//first是指向头结点的头指针 {p=first->next;//p是工作节点 pre=NULL;//pre保存p的前驱结点 因为需要把p的指针指向p的前驱结点while(p!=NULL){r=p->next;//r保存p的后驱节点  因为对p的数据域中的指针作出修改后 p的后驱节点会遗失 p->next=pre;pre=p;p=r;}first->nest=pre;}
2.通过头插法实现

void reserve3(Node *first)//first是指向头结点的头指针 {p=first->next;//预置工作节点 first->next=NULL;//原表的头结点作为新表的头结点 while(p){u=p->next;//暂存p的后继节点 p->next=first->next;//把p插到头结点之后 first->next=p;//让头结点指向p p=u; //更新p为下一个输入节点 }}