# Experimental instruction for data structure and algorithm R (2020)

Keywords: Java C C++ data structure

# preface:

LPT inner roll: Brush questions every day

# Experiment 1 linear table

1. Let the data elements in sequence table A increase in order, try to write A program to insert x into the appropriate position of the sequence table so that the table is still orderly.

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

#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10

/**
* Sequential table structure
*/
typedef struct{
int *elem; // Storage base address
int length ; // List length
int listsize; // Storage capacity
}SqList;

/**
* initialization
*/
void InitList(SqList *L){
L->elem = (int *)malloc(LIST_INIT_SIZE*sizeof(int)); // Create an empty list
L->length = 0; // Empty table length is 0
L->listsize = LIST_INIT_SIZE; // Initial storage capacity

}

/**
* input
*/
void InputData(SqList *L){
printf("Please enter the number of list elements:");
int n;
scanf("%d",&n);
/*Judge whether the list needs to be expanded*/
int *p;
p = L->elem;
if(n > L->listsize){
L->elem = (int*)realloc(L->elem, (L->listsize+LISTINCREMENT)*sizeof(int));
L->listsize += (n + LISTINCREMENT);
}
/*Input list*/
while(n!=0){
scanf("%d", p);
p ++;
n --;
L->length ++;
}

}

/**
* Output order list
*/
void OutputList(SqList *L){
int i;
int *p = L->elem;
for(i = 0; i<L->length; i ++, p ++) printf("%d ",*p);

}

/**
* Insert element
*/
void InsertElem(SqList *L,int e){
/*Overflow judgment*/
if(L->length + 1 > L->listsize){
L->elem = (int*)realloc(L->elem,(L->listsize+LISTINCREMENT)*sizeof(int));
L->listsize += LISTINCREMENT;
}

int *p = L->elem;
int *p_last = L->elem+L->length-1;
/* Find where the element is inserted*/
while(e > *p&&p<p_last) p++;

int *q ;
for(q = (L->elem)+(L->length)-1; q >= p; q--) *(q+1) = *q;

*p = e;
L->length ++;

}

int main(){

SqList  L; // Define a sequence table
InitList(&L); // initialization
InputData(&L); // input data
OutputList(&L); // Display data
printf("Insert data:");
int m;
scanf("%d", &m);
InsertElem(&L, m);
printf("\n Sequence table after insertion:");
OutputList(&L);

return 0;
}
```

2. Use the single linked list ha to store the polynomial a (x) = a0+a1x1+a2x2 +... + anxn (where aI is a non-zero coefficient), and use the single linked list hb to store the polynomial B (x) = b0+b1x1+b2x2 +... + bmxm (where bj is a non-zero coefficient). It is required to calculate C (x) = a (x) + B (x), and the results are stored in the single linked list hc. Try to write the program.

3. There are n people sitting around a round table. Now start counting from the s person, count to the m person, then start counting again from the next person, and count to the m person again. Repeat until all people are listed. The Josephus problem is: for any given n, m, s, find the sequence table of n people obtained according to the column order.

# Experiment 2 tree

1. Write recursive algorithm to calculate the number of leaf nodes in binary tree.

```#include<iostream>
using namespace std;
typedef struct TNode//Binary tree structure
{
char nodeValue;//Value of node
TNode* left;//Left subtree
TNode* right;//Right subtree
}*BiTree;
//Create a binary tree in the middle order traversal mode, and the input # means that the node is empty
void CreateBiTree(BiTree &T){
char nodeValue;
cin>> nodeValue;
//Node is not empty
if(nodeValue!='.'){
T=new TNode;
T->nodeValue=nodeValue;
CreateBiTree(T->left);
CreateBiTree(T->right);
}
else T=NULL;
}
//Calculate the number of nodes
int CountLeaf(BiTree T){
//The initial number of leaves is 0, using static variables
static int LeafNum=0;
if(T)//The tree is not empty
{
if(T->left==NULL&&T->right==NULL)//Is a leaf node
LeafNum++;//Number of leaves plus 1
else//Not a leaf node
{
CountLeaf(T->left);//Recursive statistics of leaves of left subtree
CountLeaf(T->right);//Recursive statistics of leaf number of right subtree
}
}
return LeafNum;
}
//The main function used to test,
int main(){
BiTree T;
int leafNum;
cout<<"Please enter the binary tree sequence traversed in the middle order, such as(ABC..DE.G..F...)"<<endl;
CreateBiTree(T);
leafNum=CountLeaf(T);
cout<<"The number of leaf nodes in the binary tree is:"<<leafNum<<endl;
return 0;
}

```

2. Write a recursive algorithm to find the node at the K position in the preorder sequence in the binary tree.

```#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int i ;
int k ;
int count = 0;
//Define tree structure
struct node{
char info;
};
//Replace struct with node
typedef struct node NODE;
//Create function (create)
NODE *creat(){
char x;
NODE *p;
scanf("%c",&x);  //Enter the address of the variable x
printf("%c",x);  //Output x
if(x!='.'){  //Enter. Indicates that the node is empty. Judge whether the node is empty

p=(NODE *)malloc(sizeof(NODE));
//Allocate a memory space of Node type size, and force the first address of the allocated space to Node * type
p->info=x; //Assign x to info
}
else
p=NULL;
return p;
}
//Find the K-th node data
int found(NODE* T){
if(T)
{
i++;
if(i==k)//Judge whether the input K node is the corresponding node
printf("The result is %c\n",T->info);//info store data
else
{
//Call itself repeatedly until K is found
}
}
return 0;
}

int main(){
NODE *T;  //Define a tree T
printf("Please enter a tree:\n");  //Enter a tree

T=creat();  //Create traversal
printf("k=");
scanf("%d",&k);//Read the K node to query
i=0;
found(T);

}

```

3. Implement the above example with non recursive program.

# Fig. 3 of experiment

1. Using adjacency table storage structure, write an algorithm to find the number of connected components of undirected graph.

2. Try to write a program based on the depth first search strategy of graph to judge whether there is a path from vertex Vi to Vj vertex (i ≠ j) in the directed graph stored in the form of adjacency table.

```#include <stdio.h>
#include <malloc.h>
#include <Windows.h>

int n;
//Define structure
typedef struct arcNode
{
int position;
struct arcNode *next;
}ArcNode, *ArcNode_;

typedef struct vNode
{
int mark;
ArcNode *first;
}VNode, *VNode_;
//Define function, construct number
VNode_ Structure()
{
VNode_ Chart;
int i, j, k;
ArcNode_ p, q;

printf("\n Please enter the total number of vertices of the graph to be constructed.\n");

scanf("%d", &n);

while(n<1)
{
printf("The entered data is incorrect! Please re-enter.\n");
scanf("%d", &n);
}

Chart = (VNode_)malloc(n*sizeof(VNode));

for(i=0; i<n; ++i)
{
scanf("%d", &k);
if(k != 0)
{
q = (ArcNode_)malloc(sizeof(ArcNode));
q->position = k-1;
(Chart+i)->first = q;
p = q;

scanf("%d", &k);
while(k != 0)
{
q = (ArcNode_)malloc(sizeof(ArcNode));
q->position = k-1;
p->next = q;
p = q;

scanf("%d", &k);
}
p->next = NULL;
}
else
{
Chart[i].first = NULL;
}

}
return Chart;
}

//Define functions for finding
void DFS(VNode_ Chart, int t)
{
ArcNode_ q;

if(Chart[t].mark == 0)
{
Chart[t].mark = 1;
for(q=Chart[t].first; q != NULL; q=q->next)
{
DFS(Chart, q->position);
}
}
}

void Initialize(VNode_ Chart)
{
int i;
for(i=0; i < n; i++)
{
(Chart+i)->mark = 0;
}
}

void End(VNode_ Chart)
{
int i;
ArcNode_ p, q;
for(i=0;i<n;i++)
{
p = Chart[i].first;

while(p!=NULL)
{
q = p;
p = p->next;
free(q);
}
}
free(Chart);
}
//Define main function
int main()
{
int i=0;
int count=0;
int w, v;

VNode_ Chart = Structure();
while(1){printf("Please enter the vertex to query w,v\n");
scanf("%d,%d", &w, &v);
DFS(Chart, w-1);
if(Chart[v-1].mark)
{
printf("vertex V%d，And vertex V%d Connectivity between.", w, v);
}
else
{
printf("vertex V%d，And vertex V%d There is no connection between them.", w, v);
}
printf("\n\n");

End(Chart);}
}

```

3. In the above example, if the graph is stored in the way of adjacency table, try to compile a program to realize the above algorithm.
Each element of the vertex table nodelist contains four fields:

infomarkpreout

Where mark is a boolean type, which is used to mark whether the vertex has been accessed. At the beginning, the mark field of all elements is false. For each vertex visited, the mark field is set to true. info is the vertex value, pre is the sequence number of the precursor vertex of the vertex on the access path, and out points to the edge table of the vertex.

# Experiment 4 search

1. Write a program to realize the following operations: find records with key in binary sort tree.

2. Try to rewrite the half search algorithm into a recursive algorithm.

# Ranking in Experiment 5

1. Design a direct selection sorting algorithm represented by linked list and implement it by program.
Algorithm description: the known initial sequence to be sorted is stored in a single linked list, and the head pointer head points to the first node. Find the minimum node from the sequence to be sorted, insert the head and indicate it with R. R is a sorted sequence before, and R is an unordered sequence after. Find the smallest node from the unordered sequence, insert it after r, and let r point to this node. Repeat the process until it is in order.

```#include <stdio.h>
#include <malloc.h>
#include <Windows.h>
int n;
struct Number{
int data;
struct Number* next;
};
struct Number* Creat_H(int k){
struct Number* L;
struct Number* p;
int temp,i;
p=(struct Number*)malloc(sizeof(struct Number));
L=p;
for(i=1;i<=k;i++){
scanf("%d",&temp);
p->data=temp;
if(i==k){
p->next=NULL;
break;
}
p->next=(struct Number*)malloc(sizeof(struct Number));
p=p->next;
}
return L;
}
//Sorting function
struct Number* Sort1(struct Number* p){
struct Number* max;
struct Number* min;
struct Number* temp;
struct Number* r;
int flag=0;
r=p;

do{//Initialization at the first decimal point
if(flag==0){
temp=min=max=r;
}
else{
temp=min=max=r->next;
}
while(1){//Find the decimal point
if(min->data<=max->next->data){
if(max->next->next!=NULL){
max=max->next;
}
else{
break;
}
}
else{
temp=max;//Equivalent to temp - > next = min
min=max->next;
if(max->next->next!=NULL){
max=max->next;
}
else{
break;
}
}
}
if(temp!=min){
if(min->next==NULL){
temp->next=NULL;
}
else{
temp->next=min->next;
}
if(flag==0){
r=min;
r->next=p;
p=r;
}
else{
min->next=r->next;
r->next=min;
r=min;
}
}
else{//min already points to the minimum number during initialization
if(flag==0){//Find the minimum number for the first time
r=min;
p=r;
}
else{
r=min;
}
}
flag++;//Another number
if(flag==n-1){
return p;
}
}while(1);
}
int main(){

struct Number* H;
printf("Number of data entered(Not less than 2): \n");
scanf("%d",&n);
while(n<2){
printf("The number of data you entered is less than 2. Please re-enter:\n");
scanf("%d",&n);
}
H=Creat_H(n);
H=Sort1(H);
printf("The sequence after data sorting is:\n");
while(H!=NULL){
printf("%-4d",H->data);
H=H->next;
}
printf("\n");

system("pause");
return 0;
}

```

2. The records with N keywords taken as integers are sorted so that all records with non negative keywords are ranked before those with negative keywords. It is required to use the least additional space and the time complexity of the algorithm is O(N).

```#include <stdio.h>
#include <malloc.h>
#include <Windows.h>
//Sorting function
void Sort(int* a,int m){
int i=0;
int j=m-1;
int temp;
while(i<=j){
while(i<m&&a[i]>=0){
i++;
}
while(j>=0&&a[j]<0){
j--;
}
if(i<j){
temp=a[i];
a[i]=a[j];
a[j]=temp;
i++;
j--;
}
}

}
int main(){
int n,i;
int* p;
printf("Please enter the number of data to be sorted (must be greater than 1):\n");
scanf("%d",&n);
while(n<2){
printf("The value you entered is unreasonable. Please re-enter:\n");
scanf("%d",&n);
}
p=(int*)malloc(n*sizeof(int));
for(i=0;i<n;i++){
scanf("%d",&p[i]);
}
Sort(p,n);
printf("The data after the whole sequence is:\n");
for(i=0;i<n;i++){
printf("%-4d",p[i]);
}
printf("\n");
system("pause");
return 0;
}

```

Posted by sgtpepper on Tue, 30 Nov 2021 05:01:39 -0800