需掌握的算法
顺序表
- 按元素值的查找算法,若查找成功,返回其下标,查找失败返回-1;
int findElem(Sqlist L,int x)
{
int i;
for(i=0;i<L.length;i++)
{
if(L.data[i]==x)
return i;
}
return -1;
}
- 插入数据元素,在表中p位置上插入新的元素e,若p的输入不正确,返回0;
int insertElem(Sqlist &L,int p,int e)
{
if(p<0||p>L.length||L.length==maxSize)
{
return 0;
}
for(int i=L.length-1;i>=p;i--)
{
L.data[i+1]=L.data[i];
}
L.data[i]=e;
++(L.length);
return 1;
}
- 删除表中下标为p的元素,成功发挥1,失败返回0,并将被删除的值赋给e
int deleteElem(Sqlsit &L,int p,int &e)
{
if(p<0||p>L.length||L.length==maxSize)
return 0;
e=L.data[p];
for(int i=p;i<L.length-1;i++)
{
L.data[i]=L.data[i+1];
}
--(L.length);
return 1;
}
单链表算法
- 头插法算法
void createListHead(LNode *&C,int a[],int n)
{
LNode *s;
int i;
C=(LNode*)malloc(sizeof(LNode));
C->next=NULL;
for(i=0;i<n;i++)
{
s=(LNode*)malloc(sizeof(LNode));
s->data=a[i];
s->next=C->next;
C->next=s;
}
}
- 尾插法算法
void createListTail(LNode *&C,int a[],int n)
{
LNode *r,*s;
int i;
C=(LNode*)malloc(sizeof(LNode));
C->next=NULL;
r=C;
for(i=0;i<n;i++)
{
s=(LNode*)malloc(sizeof(LNode));
s->data=a[i];
r->next=s;
r=r->next;
}
r->next=NULL;
}
- A、B是两个递增的单链表,将其合并成一个元素值非递减有序的链表C
void merge(LNode *A,LNode *B,LNode *&C)
{
LNode *p=A->next;
LNode *q=B->next;
LNode *s;
C=A;
C->next=NULL;
free(B);
s=C;
while(p!=NULL&&q!=NULL)
{
if(p->data<q->data)
{
r->next=p;
p=p-next;
r=r->next;
}
else
{
r->next=q;
q=q-next;
r=r->next;
}
}
r->next=NULL;
if(p!=NULL)
r->next=p;
if(q!=NULL)
r->next=q;
}
- A、B是两个递增的单链表,将其合并成一个元素值非递增有序的链表C
void merge(LNode *A,LNode *B,LNode *&C)
{
LNode *p=A->next;
LNode *q=B->next;
LNode *s;
C=A;
C->next=NULL;
free(B);
while(p!=NULL&&q!=NULL)
{
if(p->data<q->data)
{
s=p;
p=p->next;
s->next=C->next;
C->next=s;
}
else
{
s=q;
q=q->next;
s->next=C->next;
C->next=s;
}
}
while(p!=NULL)
{
s=p;
p=p->next;
s->next=C->next;
C->next=s;
}
while(q!=NULL)
{
s=q;
q=q->next;
s->next=C->next;
C->next=s;
}
}
- 查找链表中是否存在一个值为x的结点,若存在删除该节点并返回1,否则返回0
void findAndDelete(LNode *A,int x)
{
LNode *p,*q;
p=A;
while(p->next!=NULL)
{
if(p->next->data==x)
break;
p=p->next;
}
if(p->next==NULL)
return 0;
else
{
q=p->next;
p->next=p->next->next;
free(q);
return 1;
}
}
双链表算法
-
尾插法建立双链表
-
查找结点
-
插入结点的算法
-
删除结点的算法