线性表总结
1.从顺序表中删除重复的元素,并使剩余元素间的相对次序保存不变。
1.1 代码1
#define maxsize 50 //1
#include <iostream> //2
using namespace std; //3
typedef struct{ //4
int data[maxsize]; //5
int length; //6
}SqList; //7
typedef SqList *List; //8
void CreateSqList(List &L,int a[],int n); //9
void DispSqList(List L); //10
void DestroyList(List &L); //11
void DelSameNode(List &L) ; //12
void DestroyList(List &L){ //13
delete L; //14
} //15
int main() //16
{ //17
int i,n; //18
int a[maxsize]; //19
List L; //20
cin>>n; //21
for(i=0;i<n;i++) //22
cin>>a[i]; //23
CreateSqList(L,a,n) ; //24
DelSameNode(L) ; //25
DispSqList(L); //26
DestroyList(L); //27
} //28
void CreateSqList(List &L,int a[],int n) //创建顺序表 //29
{ //30
L=new SqList; //31
int i,m; //32
for(i=0;i<n;i++) //33
{ //34
L->data[i]=a[i]; //35
} //36
L->length=n; //37
} //38
void DispSqList(List L)//输出顺序表 //39
{ //40
int i,flag=0; //41
for(i=0;i<L->length;i++) //42
{ //43
if(flag)cout<<" "; //44
cout<<L->data[i]; //45
flag=1; //46
} //47
} //48
void DelSameNode(List &L)//删除顺序表重复元素 //49
{ //50
int i,k,j=0; //51
int flag=0; //52
for(i=1;i<L->length;i++) //53
{ //54
k=0; //55
while(k<=j&&L->data[i]!=L->data[k]) //56
k++; //57
if(k>j) //58
{ //59
j++; //60
L->data[j]=L->data[i]; //61
} //62
flag=1; //63
} //64
if(flag)L->length=j+1; //65
} //66
1.2 不懂得地方
53行到64行 算法思路有点混乱,思路不是特别清晰
分析:第i个i元素与前面j已确定无重复得j个元素进行比较,相同则不是算入无重复序列
2.一个带有表头节点的单链表,查找链表中倒数第m个位置上的节点。
2.1代码2
int Find(LinkList L, int m ) //1
{ //2
LinkList p; //3
int i=0; //4
for(p=L->next;p;p=p->next) //5
i++; //6
int n=i; //7
if(m>n||m<=0) //8
return -1; //9
for(i=0,p=L->next;p;p=p->next,i++) //10
if(i+m==n) //11
{ //12
return p->data; //13
} //14
} //15
2.2 不懂的地方
1行到15行:换成数组查找倒K项,在数组足够大的情况下,为何会超时呢
分析:先遍历链表,得出链表长度,再次遍历链表查找倒K项
下图为数组超时代码