Data Structure Review Materials

MOOC assignment topics

string pattern matching

Set the main string S='abcaabbabcabaacbacba', the pattern string P='abcabaa'

(1) Calculate the next value and nextval function value of the pattern string P;

(2) Instead of writing out the algorithm, only draw the matching process of each trip when using the KMP algorithm (using the improved nextval value) for pattern matching.

(You can refer to the matching process description form in Figure 4.3 and Figure 4.4 on page 80 of the textbook. Note the values ​​of i and j at the end of each match after each match.)

insert image description hereinsert image description here

Huffman coding

Assume that the message used for communication consists of letters in the character set {a, b, c, d, e, f, g}. The frequency of their appearance in the message is {0.31, 0.16, 0.10, 0.08, 0.11, 0.20, 0.04},

1) Design Huffman coding for these 7 letters;

2) To design an equal-length code for these 7 letters, at least how many binary digits are needed?

3) How much does Huffman coding compress the total length of the message compared to equal-length coding?

(1) slightly

(2) 3 digits

(3)

Equal length code length: (0.31+0.16+0.1+0.08+0.11+0.2+0.04)x3=3

Huffman code length: 0.31x2+0.16x3+0.1x3+0.08x4+0.11x3+0.2x2+0.04x4=2.61

(3 - 2.61) / 3 = 13%

Synthesis of graphs

There are 7 cities in a certain country, and there is no road between them, so the traffic is very inconvenient. In order to solve the problem of "difficult roads", the government decided to build roads. After research, if the relationship between these 7 cities is viewed as a graph, the letters represent the names of the cities, and the numbers represent the cost of road construction:

image-20230619114720806

(1) Please draw the adjacency list corresponding to the graph, and write the depth-first and breadth-first traversal sequences

(2) In order to save money to the greatest extent, the government only allows 6 roads to be built, and the 7 cities can be connected through these 6 roads. Please start from city A and use Prim's algorithm to carry out the 6 roads. Choose to draw the solution process.

Tip: The answer of the adjacency list of a graph is not unique, but the answer of the traversal sequence corresponding to the adjacency list is unique.

The graph is a weighted graph, and the weight information of each edge is also stored in the adjacency list.

(1)

image-20230619114826083

DFS sequence: ABCDFEG

BFS sequence: ABDGCFE

(2)

image-20230619114903034

Referring to textbook P174, it is also necessary to draw a table similar to Figure 7.17

Balanced Binary Sorting Tree

Input the elements in the table (30, 15, 28, 20, 24, 10, 68, 35, 50) in sequence to generate a balanced binary sort tree.

Please draw the construction process and indicate the type of each balance (LL type, RR type, LR type, RL type)

image-20230619115320945

hash table

Given a set of search keywords (32, 15, 7, 11, 4, 28, 56, 61, 79), the length of the hash table is m=12, please design a hash function according to the remainder The probability of finding each record is equal.

(1) Draw the hash table obtained by processing conflicts according to linear detection and then hashing (give the solution process), and calculate the average search length when the search is successful and the search fails under the condition of equal probability.

(2) Draw the hash table obtained by processing conflicts according to the chain address method, and calculate the average search lengths when the search succeeds and fails when the search is equally probable.

(1)

insert image description here

(2)

insert image description here

PTA topic

Should only test linear tables, trees

6-1 Interval deletion of linear table elements

Given a sequentially stored linear table, please design a function to delete all elements whose values ​​are greater than min and less than max. After deletion, the remaining elements in the table are stored sequentially, and their relative positions cannot be changed.

Function interface definition:

List Delete( List L, ElementType minD, ElementType maxD );
List Delete(List L, ElementType minD, ElementType maxD) {
     
     
       int i, p = 0;
       for (i = 0; i <= L->Last; i++) {
     
     
           if (L->Data[i] <= minD || L->Data[i] >= maxD) {
     
     
               L->Data[p++] = L->Data[i];
           }
       }
       L->Last = p - 1;
       return L;
}

6-2 Insertion into an ordered list

Assuming that the data elements in the sequence table are arranged in a non-decreasing order by value, try to write an algorithm to insert x into the appropriate position of the sequence table to maintain the order of the sequence table.

Function interface definition:

void ListInsertSort(SqList *L, DataType x);

Where Land xare parameters passed in by the user. LIndicates the sequence table, xwhich is the element to be inserted.

void ListInsertSort(SqList *L, DataType x) {
     
     
       int i;
       int temp = 1;

       for (i = 0; L->items[i] < x; i++) {
     
     
           temp++;
       }

       ListInsert(L,temp,x);
    
}

6-3 Merging two sorted arrays

It is required to implement a function merge to merge the ascending array a of length m and the ascending array b of length n into a new array c, and the merged array is still arranged in ascending order.

Function interface definition:

void printArray(int* arr, int arr_size);           /* 打印数组,细节不表 */
void merge(int* a, int m, int* b, int n, int* c);  /* 合并a和b为c */

Where a and b are arrays arranged in ascending order, m and n are the lengths of arrays a and b respectively; c is the merged array in ascending order.

void merge(int *a, int m, int *b, int n, int *c) {
     
     
       int i, j, k;
       while (i < m && j < n) {
     
     
           if (a[i] < b[j])
               c[k++] = a[i++];
           else
               c[k++] = b[j++];
       }
       while (i < m) {
     
     
           c[k++] = a[i++];
       }
       while (j < n) {
     
     
           c[k++] = b[j++];
       }
}

6-4 Sequence list operation set

This question requires the implementation of the operation set of the sequence table.

Function interface definition:

List MakeEmpty(); 
Position Find( List L, ElementType X );
bool Insert( List L, ElementType X, Position P );
bool Delete( List L, Position P );

where Listthe structure is defined as follows:

typedef int Position;
typedef struct LNode *List;
struct LNode {
    ElementType Data[MAXSIZE];
    Position Last; /* 保存线性表中最后一个元素的位置 */
};

The definition of each operation function is:

List MakeEmpty(): create and return an empty linear table;

Position Find( List L, ElementType X ): Returns the position of X in the linear table. Return ERROR if not found;

bool Insert( List L, ElementType X, Position P ): Insert X at position P and return true. If the space is full, print "FULL" and return false; if the parameter P points to an illegal position, print "ILLEGAL POSITION" and return false;

bool Delete( List L, Position P ): Delete the element at position P and return true. If the parameter P points to an illegal position, print "POSITION P EMPTY" (where P is the parameter value) and return false.

List MakeEmpty() {
     
     
       List list;
       list = (List) malloc(sizeof(struct LNode));
       list->Last = -1;
       return list;
}

Position Find(List L, ElementType X) {
     
     
       int i;
       for (i = 0; i < MAXSIZE; i++) {
     
     
           if (L->Data[i] == X)
               return i;
       }
       return ERROR;
}

bool Insert(List L, ElementType X, Position P) {
     
     
       int i;

       if (L->Last == MAXSIZE - 1) {
     
     
           printf("FULL");
           return false;
       }

       if (P < 0 || P > L->Last + 1) {
     
     
           printf("ILLEGAL POSITION");
           return false;
       }

       for (i = L->Last; i >= P; i--) {
     
     
           L->Data[i + 1] = L->Data[i];
       }
       L->Data[P] = X;
       L->Last++;
       return true;

}

bool Delete(List L, Position P) {
     
     
       int i;

       if (P < 0 || P > L->Last) {
     
     
           printf("POSITION %d EMPTY", P);
           return false;
       }

       for (i = P; i < L->Last; i++) {
     
     
           L->Data[i] = L->Data[i + 1];
       }
       L->Last--;

       return true;
}

6-5 Insertion of Incrementing Integer Sequence Linked List

This question requires implementing a function to insert a new integer into the increasing integer sequence linked list (leading node) and keep the order of the sequence.

Function interface definition:

List Insert( List L, ElementType X );

where Listthe structure is defined as follows:

typedef struct Node *PtrToNode;
struct Node {
    ElementType Data; /* 存储结点数据 */
    PtrToNode   Next; /* 指向下一个结点的指针 */
};
typedef PtrToNode List; /* 定义单链表类型 */

LIt is a given singly-linked list with the leading node, and the data stored in the nodes is in increasing order; the function Insertwill Xinsert Land maintain the order of the sequence, and return the linked list head pointer after insertion.

List Insert(List L, ElementType X) {
     
     
       List p, s;
       p = L;
       s = (List) malloc(sizeof(struct Node));
       s->Data = X;

       while (p->Next && p->Next->Data < X) {
     
     
           p = p->Next;
       }
       s->Next = p->Next;
       p->Next = s;

       return L;
}

6-6 Delete the even-numbered nodes of the singly linked list

This question requires the implementation of two functions, which respectively store the read data as a single linked list and delete the nodes with even values ​​in the linked list. Linked list nodes are defined as follows:

struct ListNode {
    int data;
    struct ListNode *next;
};

Function interface definition:

struct ListNode *createlist();
struct ListNode *deleteeven( struct ListNode *head );

The function createlistreads a series of positive integers from the standard input, and builds a singly linked list in the order in which they are read. When −1 is read, it means that the input is over, and the function should return a pointer to the head node of the singly linked list.

The function deletes the nodes with even values ​​in deleteeventhe singly linked list , and returns the head pointer of the resulting linked list.head

struct ListNode *createlist() {
     
     
    int m;
    struct ListNode *p, *s, *l;
    p = (struct ListNode *) malloc(sizeof(struct ListNode));

    scanf("%d", &m);
    if (m == -1)
        return NULL;
    p->data = m;
    p->next = NULL;
    s = p;

    while (1) {
     
     
        scanf("%d", &m);
        if (m == -1)
            break;
        l = (struct ListNode *) malloc(sizeof(struct ListNode));
        l->data = m;
        l->next = NULL;
        s->next = l;
        s = l;
    }
    return p;

}

struct ListNode *deleteeven(struct ListNode *head) {
     
     
    struct ListNode *p = NULL, *s = NULL;

    while (head && head->data % 2 == 0) {
     
     
        p = head;
        head = head->next;
        free(p);
    }
    if (head == NULL)
        return NULL;
    s = head;
    while (s->next) {
     
     
        if (s->next->data % 2 == 0)
            s->next = s->next->next;
        else
            s = s->next;
    }
    return head;
}

6-7 Create a linked list with reverse data

This question requires the implementation of a function to create a linked list in the reverse order of the input data.

Function interface definition:

struct ListNode *createlist();

The function createlistuses scanfto get a series of positive integers from the input, and when it reads −1, it means the end of the input. Create a linked list in the reverse order of the input data, and return the linked list head pointer. The linked list node structure is defined as follows:

struct ListNode {
    int data;
    struct ListNode *next;
};
struct ListNode *createlist() {
     
     
    int m;
    struct ListNode *head, *p;
    head = (struct ListNode *) malloc(sizeof(struct ListNode));
    head->next = NULL;

    while (1) {
     
     
        scanf("%d", &m);
        if (m == -1)
            break;
        p = (struct ListNode *) malloc(sizeof(struct ListNode));
        p->next = head->next;
        p->data = m;
        head->next = p;
    }
    return head->next;
}

6-8 Find the last mth element of the linked list

Please design an algorithm that is as efficient as possible in terms of time and space, and find the penultimate m (>0) element of the linear list stored in a chain without changing the linked list.

Function interface definition:

ElementType Find( List L, int m );

where Listthe structure is defined as follows:

typedef struct Node *PtrToNode;
struct Node {
    ElementType Data; /* 存储结点数据 */
    PtrToNode   Next; /* 指向下一个结点的指针 */
};
typedef PtrToNode List; /* 定义单链表类型 */

LIs the given singly linked list with the leading node; the function Findwill return Lthe penultimate melement without changing the original linked list. If no such element exists, an error flag is returned ERROR.

ElementType Find(List L, int m) {
     
     
    int i;
    PtrToNode p, s;
    p = s = L;

    for (i = 0; i < m; i++) {
     
     
        p = p->Next;
        if (!p)
            return ERROR;
    }
    while (p) {
     
     
        s = s->Next;
        p = p->Next;
    }

    return s->Data;
}

6-9 Merge of two ordered linked list sequences

This question requires the implementation of a function that combines the increasing integer sequences represented by two linked lists into a non-decreasing integer sequence.

Function interface definition:

List Merge( List L1, List L2 );

where Listthe structure is defined as follows:

typedef struct Node *PtrToNode;
struct Node {
    ElementType Data; /* 存储结点数据 */
    PtrToNode   Next; /* 指向下一个结点的指针 */
};
typedef PtrToNode List; /* 定义单链表类型 */

L1L2The sum is a given singly linked list with the leading node, and the data stored in the nodes is in increasing order; the function will Mergecombine L1the L2sum into a non-decreasing sequence of integers. The nodes in the original sequence should be used directly, and the linked list head pointer of the merged leading node should be returned.

List Merge( List L1, List L2 )
{
     
     
    List pa,pb,pc;
    pa=L1->Next;
    pb=L2->Next;
    List L=(List)malloc(sizeof(List));
    pc=L;
    
    while(pa&&pb)
    {
     
     
        if(pa->Data>pb->Data)
        {
     
     
            pc->Next=pb;
            pb=pb->Next;
        }
        else{
     
     
            pc->Next=pa;
            pa=pa->Next;
        }
        pc=pc->Next;
    }
    
    if(pa)
        pc->Next = pa;
    if(pb)
        pc->Next = pb;
    L1->Next=NULL;
    L2->Next=NULL;
    
    return L;
}

6-10 Binary tree traversal

The problem requires 4 traversals of a given binary tree.

Function interface definition:

void InorderTraversal( BinTree BT );
void PreorderTraversal( BinTree BT );
void PostorderTraversal( BinTree BT );
void LevelorderTraversal( BinTree BT );

where BinTreethe structure is defined as follows:

typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
    ElementType Data;
    BinTree Left;
    BinTree Right;
};

The four functions are required to print out the contents of the nodes in the order of access, and the format is a space followed by a character.

void InorderTraversal(BinTree BT) {
     
     //中序遍历
    if (BT) {
     
     
        InorderTraversal(BT->Left);
        printf(" %c", BT->Data);
        InorderTraversal(BT->Right);
    }
}

void PreorderTraversal(BinTree BT) {
     
     //先序遍历
    if (BT) {
     
     
        printf(" %c", BT->Data);
        PreorderTraversal(BT->Left);
        PreorderTraversal(BT->Right);
    }
}

void PostorderTraversal(BinTree BT) {
     
     //后序遍历
    if (BT) {
     
     
        PostorderTraversal(BT->Left);
        PostorderTraversal(BT->Right);
        printf(" %c", BT->Data);
    }
}

void LevelorderTraversal(BinTree BT) {
     
     
    BinTree B[100];//结构体数组
    BinTree T;
    int i = 0, j = 0;
    if (!BT)return;//树为空,返回
    if (BT)//不为空
    {
     
     
        B[i++] = BT;//根节点入队
        while (i != j)//队列不空
        {
     
     
            T = B[j++];//出队
            printf(" %c", T->Data);
            if (T->Left) B[i++] = T->Left;
            if (T->Right) B[i++] = T->Right;
        }
    }
} 

6-11 Non-recursive traversal of a binary tree

This question requires a non-recursive method to implement three traversals of a given binary tree.

Function interface definition:

void InorderTraversal( BinTree BT );
void PreorderTraversal( BinTree BT );
void PostorderTraversal( BinTree BT );

where BinTreethe structure is defined as follows:

typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
    ElementType Data;
    BinTree Left;
    BinTree Right;
    int flag;
};

The three functions are required to print out the contents of the nodes according to the access order, and the format is a space followed by a character.

void InorderTraversal( BinTree BT ){
     
     //中序遍历
    BinTree T=BT;
    Stack S =CreateStack();
    while(T||!IsEmpty(S)){
     
     
        while(T!=NULL){
     
     
            Push(S,T);
            T=T->Left;
        }
        T=Pop(S);
        printf(" %c",T->Data);
        T=T->Right;
    }
}
void PreorderTraversal( BinTree BT ){
     
     //先序遍历
    BinTree T=BT;
    Stack S =CreateStack();
    while(T||!IsEmpty(S)){
     
     
        while(T!=NULL){
     
     
            Push(S,T);
            printf(" %c",T->Data);
            T=T->Left;
        }
        T=Pop(S);
        T=T->Right;
    }
}
void PostorderTraversal( BinTree BT ){
     
     //后序遍历
    BinTree T=BT;
    Stack S =CreateStack();
    while(T||!IsEmpty(S)){
     
     
        while(T!=NULL){
     
     
            T->flag=0;
            Push(S,T);
            T=T->Left;
        }
        T=Peek(S);
        if(T->flag==0){
     
     
            T->flag++;
            T=T->Right;
        }
        else{
     
     
            T=Pop(S);
            printf(" %c",T->Data);
            T=NULL;
        }
    }
}

6-12 Find the height of binary tree

This question requires the height of a given binary tree.

Function interface definition:

int GetHeight( BinTree BT );

where BinTreethe structure is defined as follows:

typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
    ElementType Data;
    BinTree Left;
    BinTree Right;
};

The function is required to return the height value of the given binary tree BT.

int GetHeight(BinTree BT) {
     
     
   int lNum, rNum, Height;
   if (BT) {
     
     
       lNum = GetHeight(BT->Left);
       rNum = GetHeight(BT->Right);
       if (lNum > rNum)
           Height = lNum;
       else
           Height = rNum;
       return Height + 1;
   } else {
     
     
       return 0;
   }
}

6-13 Depth-first traversal of an adjacency matrix memory graph

Try to implement a depth-first traversal of an adjacency matrix storage graph.

Function interface definition:

void DFS( MGraph Graph, Vertex V, void (*Visit)(Vertex) );

where MGraphis the graph stored by the adjacency matrix, defined as follows:

typedef struct GNode *PtrToGNode;
struct GNode{
    int Nv;  /* 顶点数 */
    int Ne;  /* 边数   */
    WeightType G[MaxVertexNum][MaxVertexNum]; /* 邻接矩阵 */
};
typedef PtrToGNode MGraph; /* 以邻接矩阵存储的图类型 */

The function DFSshall Vtraverse the graph recursively, depth-first, starting from the vertex , and visit each vertex Graphwith a function defined by the referee . VisitWhen visiting adjacent points, it is required to follow the sequence number increasing order. The title is guaranteed Vto be a legal vertex in the graph.

void DFS(MGraph Graph, Vertex V, void (*Visit)(Vertex)) {
     
     
   Vertex i;
   Visit(V);
   Visited[V] = true;
   for (int i = 0; i < Graph->Nv; i++) {
     
     
       if (Graph->G[V][i] == 1 && !Visited[i]) {
     
     
           DFS(Graph, i, Visit);//进行递归
       }
   }
}

6-14 Breadth-first traversal of an adjacency list storage graph

The content of the picture may not be tested, you can take a look

Try to implement the breadth-first traversal of the adjacency list storage graph.

Function interface definition:

void BFS ( LGraph Graph, Vertex S, void (*Visit)(Vertex) );

where LGraphis the graph stored in the adjacency list, defined as follows:

/* 邻接点的定义 */
typedef struct AdjVNode *PtrToAdjVNode; 
struct AdjVNode{
    
    
    Vertex AdjV;        /* 邻接点下标 */
    PtrToAdjVNode Next; /* 指向下一个邻接点的指针 */
};

/* 顶点表头结点的定义 */
typedef struct Vnode{
    
    
    PtrToAdjVNode FirstEdge; /* 边表头指针 */
} AdjList[MaxVertexNum];     /* AdjList是邻接表类型 */

/* 图结点的定义 */
typedef struct GNode *PtrToGNode;
struct GNode{
    
      
    int Nv;     /* 顶点数 */
    int Ne;     /* 边数   */
    AdjList G;  /* 邻接表 */
};
typedef PtrToGNode LGraph; /* 以邻接表方式存储的图类型 */

The function BFSshould perform a breadth-first search on Sthe graph stored in the adjacency list starting from the vertex Graph, and use the function defined by the referee Visitto access each vertex when traversing. When visiting adjacency points, it is required to visit in order of adjacency list. The title is guaranteed Sto be a legal vertex in the graph.

void BFS(LGraph Graph, Vertex S, void (*Visit)(Vertex)) {
     
     
   Visited[S] = true;//标记起始点
   Visit(S);
   int queue[1000], front = 0, rear = 0;
   queue[rear++] = S;//起始点入队列
   PtrToAdjVNode temp;//temp就代表当前点的邻接点的下标
   while (front < rear) {
     
     //队伍不为空
       temp = Graph->G[queue[front++]].FirstEdge;
       while (temp) {
     
     
           int p = temp->AdjV;//把temp中的下标提取出来
           if (!Visited[p]) {
     
     //如果p点没有被标记的话
               Visited[p] = true;
               Visit(p);
               queue[rear++] = p;//储存在队列中
           }
           temp = temp->Next;//指向下一个邻接点
       }
   }
}

GNode LGraph; /* graph type stored in adjacency list */


**函数`BFS`应从第`S`个顶点出发对邻接表存储的图`Graph`进行广度优先搜索,遍历时用裁判定义的函数`Visit`访问每个顶点。当访问邻接点时,要求按邻接表顺序访问。题目保证`S`是图中的合法顶点。**

>```c
>void BFS(LGraph Graph, Vertex S, void (*Visit)(Vertex)) {
>    Visited[S] = true;//标记起始点
>    Visit(S);
>    int queue[1000], front = 0, rear = 0;
>    queue[rear++] = S;//起始点入队列
>    PtrToAdjVNode temp;//temp就代表当前点的邻接点的下标
>    while (front < rear) {//队伍不为空
>        temp = Graph->G[queue[front++]].FirstEdge;
>        while (temp) {
>            int p = temp->AdjV;//把temp中的下标提取出来
>            if (!Visited[p]) {//如果p点没有被标记的话
>                Visited[p] = true;
>                Visit(p);
>                queue[rear++] = p;//储存在队列中
>            }
>            temp = temp->Next;//指向下一个邻接点
>        }
>    }
>}

Guess you like

Origin blog.csdn.net/qq_61228493/article/details/131318484