【数据结构与算法分析】学习笔记课后答案第三章3.15自调整表

3.15自调整表:所有的插入都在表头进行,查找某元素时只需将某元素移到表头。
a、写出自调整表的数组实现

#include <stdio.h>
#include <stdlib.h>

#define MAX 10
typedef struct node
{
    
    
    int* A;
    int length;
    int Max;
}*List,List1;//qnode,*pnode;
void init(List L)
{
    
    
    L->A=(int*)malloc(MAX*sizeof(int));
    L->Max=MAX;
    L->length=0;
    for(int i=0;i<L->Max;i++)
        L->A[i]=-1;
}
void Insert(List L,int x)
{
    
    
    int i;
    if(L->Max<=L->length)
        printf("out of space!");
    else
    {
    
    
        if(L->A[0]==-1)
        {
    
    
            L->A[0]=x;
            L->length++;
        }
        else 
        {
    
    
            for(i=L->length-1;i>=0;i--)//把所有数字往后移动一个位置
                L->A[i+1]=L->A[i];
            L->A[0]=x;
            L->length++;
        }
    }
}
void PrintList(List L)
{
    
    
    for(int i=0;i<L->length;i++)
        printf("%d",L->A[i]);
    
}
void Find(List L,int x)
{
    
    
    int i=0;
    while(L->A[i]!=x&&L->A[i]!=-1)
        i++;
    if(L->A[i]==x)
    {
    
    
       for(int j=i;j>=0;j--)
            L->A[j]=L->A[j-1];
        L->A[0]=x; 
    }
    else{
    
    
        printf("out of space!");}
}
int main()
{
    
    
    List1 L;
    init(&L);
    Insert(&L,1);
    Insert(&L,2);
    Insert(&L,3);
    Insert(&L,4);
    Insert(&L,5);
    Insert(&L,6);
    Find(&L,2);
    Find(&L,7);
    PrintList(&L);
    return 0;
}
 

b、写出自调整表的链表实现

#include <stdio.h>
#include <stdlib.h>
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
 struct Node
{
    
    
    int Element;
    Position next;
};
List init()
{
    
    
    List L;
    L=(List)malloc(sizeof(struct Node));
    L->next=NULL;
    return L;
}
void Insert(List L,int x)
{
    
    
    Position pos,head;
    head=L;
    pos=(List)malloc(sizeof(struct Node));
    pos->Element=x;
    if(head->next==NULL)
    {
    
    
        head->next=pos;
        pos->next=NULL;
    }
    else
    {
    
    
        pos->next=head->next;
        head->next=pos;
    }
}
void PrintList(List L)
{
    
    
    Position pos=L->next;
    while(pos!=NULL)
    {
    
    
        printf("%d",pos->Element);
        pos=pos->next;
    }
}
Position FindPrevious(List L,int x)
{
    
    
    Position pos;
    pos=L;
    while(pos->next!=NULL&&pos->next->Element!=x)
        pos=pos->next;
    return pos;
}
Position Find(List L,int x)
{
    
    
    Position pos,head,previous;
    head=L;
    previous=FindPrevious(L,x);
    if(previous->next!=NULL)
    {
    
    
	    pos=previous->next;
	    previous->next=pos->next;
	    pos->next=head->next;
	    head->next=pos;
	    return pos;
    }
    else
    	return NULL;
}
int main()
{
    
    
    List L;
    L=init();
    Insert(L,1);
    Insert(L,2);
    Insert(L,3);
    Insert(L,4);
    Insert(L,5);
    Insert(L,6);
    L=Find(L,2);
    L=Find(L,6);
    PrintList(L);
    return 0;
}
 

猜你喜欢

转载自blog.csdn.net/su_1998/article/details/121907137
今日推荐