数据结构试题(英文版)C

合集下载

数据结构 英文试题

数据结构 英文试题

以下是一份关于数据结构的英文试题,供您参考:1. What is the difference between an array and a linked list?Answer: An array and a linked list are two fundamental data structures used in computer science. An array is a linear data structure that stores elements in a consecutive memory location. It has a fixed size and the elements are accessed by their indices. On the other hand, a linked list is a dynamic data structure that consists of a set of nodes where each node contains the data and a reference (pointer) to the next node. The size of a linked list can vary dynamically and the elements are accessed in the order of their appearance.2. Explain the operation of binary search tree.Answer: A binary search tree is a tree-like data structure in which each node has at most two children, usually referred to as the left child and the right child. The value of each node in the binary search tree is greater than or equal to the value of all nodes in its left subtree and less than or equal to the value of all nodes in its right subtree. This property allows for efficient search, insertion, and deletion operations in the binary search tree. The search operation starts from the root node and compares the value with the target value, following the appropriate branch based on the comparison result until the target value is found or the appropriate action is taken. Insertion and deletion operations also involve maintaining the binary search tree property by adjusting the tree accordingly.3. What is the difference between a stack and a queue?Answer: A stack and a queue are two fundamental data structures used in computer science. A stack is a linear data structure that follows the Last In First Out (LIFO) principle. It allows the addition and removal of elements only at one end, usually referred to as the top of the stack. Elements are added to or removed from the stack using the push and pop operations, respectively. On the other hand, a queue is a linear data structure that follows the First In First Out (FIFO) principle. It allows the addition of elements at one end (rear) and removal of elements at the other end (front). Elements are added to or removed from the queue using the enqueue and dequeue operations, respectively.。

英文版数据结构算法题

英文版数据结构算法题

1.Suppose we have a linked list.Eack node has three parts: one data field and twolinked fields.The list has been linked by the first linked field link1,but the list is disorder.Try your best to sort the list with the second linked field into an increasing list.算法:int creasort(struct node &head){if (head.link1 == NULL) //没有结点return ERROR;head.link2 = head.link1; //设排列链表的第一个结点head.link2->link2 = NULL;p = head.link1->link1; //p为链表的第二个结点q = head; //q代表p插入位置的前一个结点if (!p) //只有一个结点return OK;while (p){while ( q->link2 && (q->link2->data < p->data)) //找查找入位置q = q->link2;if (!q->link2) //插在最后{q->link2 = p;}else //插在队列中间{p->link2 = q->link2;q->link2 = p;}p = p->link1;q = head;}return OK;}2.Suppose we have a sequence with the terminal character @.The format of thesequence can be S1&S2,S1 and S2 do not contain ‘&’, S2 is the reverse sequence of S1.Try to write an algorithm to check the sequence if the format of the sequence obeys the above fules then the function return TRUE otherwise FALSE.算法://s为待检查的字符串int checkrules(char *s){len = strlen(s);//用string.h自带函数取字符串s的长度if (len % 2 == 0) //字符串是偶数return FALSE;i = 0; //i指向字符串第一个字符n = len - 1;//n指向字符串最后一个字符while (i < len / 2 && ( s[i] != '&' || s[n] != '&')) //对半劈{if (s[i] == s[n]){i++;n--;}elsebreak;}if (i == len / 2 && s[i] == '&') //i指向中间元素且必须是’&’return TRUE;elsereturn FALSE;}3.Suppose we have a double-linked ciroular list L.Eack node has four fields:twolinked fiels pre and next, one data field data and one frequency field freq.At the beginning the initial value of freq is 0 and after each opeation Locate(L,x),the value in frequency field of x plus 1,and then sort the list according to freq into a non-increasing list.The node which is most frequently accessed is the first node after the head node.算法:void Locate(struct doulin L, int x){struct doulin *; //访问时用到的遍历指针if (x > L.data) //无效的访问return;p = &L; //定位,p指向已经访问的指针while(x--){p = p->next;}p->freq++;//因为形参L不在循环链表里,因此要用L.pre->next表示循环链表的头结点while (p->pre ->freq < p->freq && p->pre != L.pre->next){p->data <-> p->pre->data;p->freq <-> p->pre->freq;}}4.Suppose we have a disordered list of integers.The list has been stored in a stack.You are supposed to sort the list with queue.算法://表示将from队的元素倒到to中void QueToQue(Queue *from, Queue *to, int ns){ tag = 0; //用于标注要排列的数是否进栈while (!QueueEmpty(from)){ DeQueue(from, &nq); //nq用于存取出队元素if ((tag == 0 && nq > ns) || tag == 1) //不能入队EnQueue(to, nq);else //可以入队了{ tag = 1; //设置标志tag为1,表示已经入队了EnQueue(to, ns);EnQueue(to, nq);}}if (tag == 0) //当ns比队中任何数都大时EnQueue(to, ns);}//将队列from中的元素倒到to栈中void QueToStack(Queue *from, Stack *to){ while (!QueueEmpty(from)){ DeQueue(from, &nq);Push(to, nq);}}//排序的本体void sort(Stack *S){ InitQueue(&Q1); InitQueue(&Q2); //初始化两个队列Q1,Q2Pop(S, &ns); EnQueue(&Q1, ns); //先将一个元素出队进栈while (!StackEmpty(S)){ Pop(S,&ns);if (!QueueEmpty(&Q1)) //若Q1队列不空(即Q2队列为空)QueToQue(&Q1, &Q2, ns);else //若Q2队列为空(即Q1队列不为空)QueToQue(&Q2, &Q1, ns);}if (!QueueEmpty(&Q1)) //Q1不为空,也就是要把Q1队载入栈QueToStack(&Q1, S);elseQueToStack(&Q2, S);}5.颜色排列的算法://colors是颜色数组,number是数组大小void colorsort(int *colors, int number){i = 0, j = number – 1;while (colors[i] == 1) //找到第一个非1的单元i++;while (colors[j] == 3) //找到最后一个非3的单元j--;k = i; //遍历指针设为iwhile(k <= j){switch (colors[k]){case 1: colors[k]<->colors[i];i++; k++;break;case 2: k++;break;case 3: colors[k]<->colors[j];j--;break;}}}。

C程序设计英文试题

C程序设计英文试题

C程序设计英文试题第1页Section 1: Single Choice(2 mark for each item, total 20 marks)1. The precedence of operator _____ is the lowest one.A.? : B.== C.+= D.&2. _____ is correct if it is used as a character constant.A.‟\‟ B.'\080' C.'%d' D.0xa3. According to the declaration: char c1=92,c2=92; the value of expression _____ is 0. A.c1^c2 B.c1&c2 C.~c2 D.c1|c24. According to the declaration: int x=11; the value of expression (x++*1/3) is_____.A.3 B.4 C.0 D.3.6675. The value of expression sizeof("\num=%d\t") is ______.A.7 B.8 C.9 D.106. In the following assignments or initialization, ______ is wrong.A.char s[ ]="hello"; B.char s[10]; s="hello";C.char *p="hello"; D.char *p; p="hello";7. The following code fragment prints out ______.#define MA(x, y) (x)*(y)int i = 2;i = 3/MA(i, i+2)+5;printf(“%d\n”, i);A.5 B.8 C.9 D.118. static struct {int x, y[3];} a[3] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}}, *p;p = a+1;The value of expression *((int *)(p+1)+2) is ______.A.3 B.7 C.10 D.119. After running the following code fragment, the value of s is ______.int i=5, s=0;《C Programming》TEST PAPER, Jan 22, 2005 2 / 8do if (i%2) continue; else s+=i; while (--i);A.15 B.9 C.6 D.510. According to the declaration: int (*p)[10], p is a(n) ______.A.pointer B.array C.function D.element of arraySection 2: Fill in the blanks(2 mark for each item, total 30 marks)1. The value of expression 1+4/5+15<7+4%5+(8,10) is ______.2. The value of expression !!10 is _____.3. The value of expression 3>2>1 is _____.4. The value of expression ~(-1<<1) is ______.5. The statement for (i=1; i<=9; i++) printf(“%3d”, ______);prints out the following numbers: 1 4 7 10 13 16 19 22 25.6. According to the declaration: int a[10], *p=&a[1]+2; the last element of array a is p[__].7. Write the declaration_____ with typedef, which makes PA a synonym for a characterpointer 第2页array, which contains 100 elements.8. The following code fragment prints out _____.static int a[3][4]={{1,2,3},{4,5,6}};printf(“%d”,a[0][5]);9. The following code fragment prints out _____.char a[]={“678”,”45”},**p=a+1;printf(“%s,%c”,*p,**p-1);10. The following code fragment prints out _____.int *p, *q, k = 1, j=10 ;p=&j; q = &k ; p = q ; (*p)++;printf("%d",k);11. The following program prints out _____.#include <stdio.h>void f(int *x,int *y){ int *p;p=x; x=y; y=p;}void main(){ int x=1, y=2;f(&y, &x);printf("%d, %d", x, y);}12. The following program prints out _____.#include <stdio.h>#include <string.h>main(){ char st[20]=”hello\0world!”;《C Programming》TEST PAPER, Jan 22, 2005 3 / 8printf(“%d,%d\n”,strlen(st),sizeof(st));}13. To execute the command: prog 123 456 ABC, the value of *(++argv[2]) is_____.14. The following program fragment prints out _____.int i;int f(int x){ static int k = 0;x+=k++;return x;}i=f(2);i=f(3);printf(“%d”,i);15. The following program fragment prints out _____.int f(int x){ return ((x>0)? x*f(x-1):3); } 第3页printf(“%d”,f(f(1)));Section 3: Read each of the following programs and answer questions (5marks for each item, total marks: 30)1.The output of the following program is _______.#include <stdio.h>void main(){int i,j,k=19;while (i=k-1) {k-=3;if(k%5==0) { i++; continue; }else if(k<5) break;i++;}printf(“i=%d,k=%d\n”,i,k);}2.When input: AabD <ENTER>, The output of the following program is _______.#include <stdio.h>void main(){char s[81];int i=0;gets(s);《C Programming》TEST PAPER, Jan 22, 2005 4 / 8while (s[i]!=…\0‟){if(s[i]<= ‟z‟&&s[i]>= ‟a‟)s[i]= ‟z‟+‟a‟-s[i];i++;}puts(s);}3.The output of the following program is _______.#include <stdio.h>int x,y,z,w;void p(int x, int *y){ int z;++x;++*y;z=x+*y;w+=x;printf(“%2d%2d%2d%2d#”, x,*y,z,w);}void main()p(y, &x);printf(“%2d%2d%2d%2d\n”, x,y,z,w);}4.The output of the following program is _______.#include <stdio.h>#define F(k) k+3.14#define P(a) printf("a=%d\n", (int)(a))#define P1(a) P(a);putchar('\n');#define P2(a, b) P(a);P1(b);void main(){int x = 1;{int x = 2;P(x*F(2));}{for (; x < 10; x += 50)P2(x, 9.15*x+32);}《C Programming》TEST PAPER, Jan 22, 2005 5 / 8}5.When input: this is a test.<ENTER>, The output of the following program is _______. #include <stdio.h>#define TRUE 1#define FALSE 0int change(char *c,int status);void main(){int flag=TRUE;char ch;do{ch=getchar();flag=change(&ch,flag);putchar(ch);} while(ch!=‟.‟);printf(“\n”);}int change(char *c,int status){if(*c==‟ …) return TRUE;if(status&&*c<=‟z‟&&*c>=‟a‟) *c+=‟A‟-…a‟;return FALSE;6.There are three text files f1,f2 & f3, each of them contains some characters as following: file name contentsf1 aaa!f2 bbb!f3 ccc!Compiling the following C source codes, and linking the related object codes, an executablecommand file ex12.exe will be produced. To execute the command at DOS prompt: ex12 f1f2 f3<ENTER>,the output is: .#include <stdio.h>main(int argc, char *argv[]){FILE *fp;void sub(FILE *);int i=1;while (--argc>0)if ((fp=fopen(argv[i++],“r”))==NULL) {printf(“Cannot open file!\n”);《C Programming》TEST PAPER, Jan 22, 2005 6 / 8exit(1);} else {sub(fp);fclose(fp);}}void sub(FILE *fp){char c;while((c=getc(fp))!=…!‟) putchar(c+1);}Section 4: According to the specification, complete each program (2 mark for each blank, total: 20 marks)1 .The following program is to calculate the value of “e” according to the formula= + + + +Λ3!12!11!e 1 1 , while the value of the last item must be less than 10- 6.#include <stdio.h>main()int i;double e,item;(1) ;item=1.0;for (i=1; (2) ;i++) {item/=(double)i;e+= (3) ;}printf(“e=%f\n”,e);}2.The following program deletes the non-nested comments which be included between /* and */from the C source program file exam.c, and stores the results in the file exam.out.#include <stdio.h>void delcomm(FILE *fp1,FILE *fp2){int c,i=0;while(( (4) )!=EOF)if (c==…\n‟)fprintf(fp2,“\n”);else《C Programming》TEST PAPER, Jan 22, 2005 7 / 8switch(i){case 0:if(c==…/‟) i=1;else fprintf(fp2,“%c”,c);break;case 1:if(c==…*‟) i=2;else {fprintf(fp2,“/%c”,c);i=0;}break;case 2:if(c==…*‟) i=3;break;case 3:i=(c==…/‟)? (5) ;break;}}void main()FILE *fp1,*fp2;fp1=fopen(“exam.c”,“r”);fp2=fopen(“exam.out”,“w”);delcomm( (6) );(7) ;return;}3.Given: the pointer head points to the first node of the simple list. The following function del()deletes the first node which value is equal to num from the simple list.#include <stdio.h>struct student {int info;struct student *link;};struct student *del(struct student *head,int num){struct student *p1,*p2;if(head==NULL)《C Programming》TEST PAPER, Jan 22, 2005 8 / 8printf(“\nlist null!\n”);else {p1=head;while( (8) ) {p2=p1;p1=p1->link;}if(num==p1->info){if(p1==head) (9) ;else (10) ;printf(“delete:%d\n”,num);} elseprintf(“%d not been found!\n”,num);}return(head);。

数据结构样卷2(英文)

数据结构样卷2(英文)

重庆大学 数据结构 课程样卷2开课学院: 计算机学院 课程号: 18001035 考试日期:考试方式:考试时间: 120 分钟一. Single choice1. The linear list (a1, a2, ... an), which is in Sequential Storage , whenwe delete any node, the average number of moving nodes ( ). A. n B. n/2 C. (n-1)/2 D. (n+1)/2 2. Which is wrong among the following statements ( ).A. Data element is the basic unit of the dataB. Data element is the smallest unit of the dataC. Data can be composed of a number of data elementsD. Data items can be composed of a number of data elements3. To insert a data element in a linear structure data conveniently, thebest data structure is ( ).A. Sequential storageB. Linked storageC.Index storageD. Hash storage4. If insert a new node into the doubly linked list which the number ofnodes is n, the measurement level of time complexity is ( ).A.O(1)B. O(n)C. O(nlog 2n)D. O(n 2)5. In virtue of a child’s Brother linked lists as a tree, if we want tofind the fifth child of the node x, as long as finding the first child of x, and then ( ).A. pointer scans 5 nodes continuously from the child domainB. pointer scans 4 nodes continously from the child domainC. pointer scans 5 nodes continously from the brother domainD. pointer scans 4 nodes continously from the brother domain 6. The character of Tree structure is: a node can have( )A. More than one direct pre-trendB. More than one direct successorsC. More than one pre-trendD. A successor7. Assume that there are 13 numbers, they form a Huffman tree, calculatethe number of nodes on this Huffman tree ( ). A. 13 B. 12 C. 26 D. 258. A spanning tree of the undirected connected graph is a ( ) whichcontains the whole vertices of this connected graph.A. Minimal connected subgraphB. Minimal subgraphC. Significantly connected sub-graphD. Significantly sub-graph 9. Which is wrong in the following statements ( ).A. Each vertex is only visited once during the graph traversal.B. There are two methods, Depth-First Search and Breadth-First Search,to traverse a graph.C. Depth-First Search of a graph isn ’t fit to a directed graphD. Depth-first search of a graph is a recursive process10. In sequential search algorithm of static table, if we set up a sentryat the head of a list, the right way to find the element is ( ) A. Looking for the data element from the first element to the back B. Looking for the data element from the second element to the back C. Looking for the data element from the (n+1)th element to the front D. I t is nothing to do with the search for order11. In order to find the number 85 in an ordered list(18,20,25,34,48,62,74,85), how many times do we need to compare( ) A.Once B. Twice C. 3 times D. 4 times12. Assume that the length of Hash table is m=14, Hash function H(key) =key % 11. There have been 4 nodes in the table, and their addresses are: 4,5,6,7. Other addresses are NULL. In virtue of quadratic probing re-hash to deal with conflict, calculate the address of node whose keyword is 9 ( ).A. 8B. 3C. 5D. 913. Using Quicksort to sort the following four sequences, and choose the命题人:组题人:审题人:命题时间:教务处制学院 专业、班 年级 学号 姓名公平竞争、诚实守信、严肃考纪、拒绝作弊封线密first element as the benchmark to divide. During the first division,in the following sequences which need to move the most times ( )A.70,75,82,90,23,16,10,68B.70,75,68,23,10,16,90,82C.82,75,70,16,10,90,68,23D.23,10,16,70,82,75,68,9014.There are 10000 elements in a sequence, the best way to get the very smallest 10 elements in the sequence is ( ).A. QuicksortB. HeapsortC. Insertion sortD. Merge sort15.If the sequence is almost in order, take compare times of key code and move times of key code into account, the best way to sort is( )A. Merge sortB. Insertion sortC. Straight selection sortD.Quicksort二.Fill the blanks1.In order to insert a new node s after the node which pointer q points to in a circular doubly linked list, we need to execute the followingstatements:s->prior=q; s->next=q->next; _____________________;q->next=s;2.In the doubly linked list, if d is a pointer points to a node in the list, then:d->next->__________=d->prior->__________=__________;3.Stack can be considered as an operation restricted linked list ,one end that can insert and remove is called _____________。

数据结构样卷1(英文)答案by郑

数据结构样卷1(英文)答案by郑

重庆大学 数据结构 课程 样卷1开课学院: 计算机学院 课程号: 18001035 考试日期:考试方式:考试时间: 120 分钟一. Single choice1. In data structure, we logically divide the data into__C_____。

A. Dynamic structure and the static structureB. Sequence structure and chain structureC. Linear structure and non-linear structureD. The internal structure and external structure2. For a singly linked list with a head node pointer, The condition todetermine whether it is empty is__B_____。

A. head == NULLB. head->next == NULLC. head->next == headD. head != NULL3. In order to prevent Pseudo-overflow, we should___D____。

书上好像没有Pseudo-overflow 的内容,这道题我是猜的A. Define enough storage spaceB. Dequeue as soon as possibleC. Enqueue as soon as possibleD. Use circular queue4. Assuming data K1! =K2, After processed by a hash function H, it isH(K1)=H(K2), then the K1, K2 are known as the H’s __A_____。

华东师范大学大一计算机专业数据结构期中英文考卷及答案 (1)

华东师范大学大一计算机专业数据结构期中英文考卷及答案 (1)

华东师范大学期中试卷20XX—20xx学年第二学期课程名称:______数据结构_____姓名:___________________ 学号:__________________专业:___________________ 年级/班级:__________________课程性质:专业必修一、单项选择题(共21分,每题3分)1. Stack has the property called last in and first out, then which of the following describes the property of Queue?a) Last in and first outb) First in and last outc) First in and first out2. A list of items from which only the item most recently added can be removed is known as a ( )a) stackb) queuec) circular linked listd) list3. If the following function is called with a value of 2 for n, what is the resultingoutput?void Quiz( int n ){if (n > 0){cout << 0;Quiz(n - 1);cout << 1;Quiz(n - 1);}}a) 00011011b) 11100100c) 10011100d) 01100011e) 0011014. What is the value of the postfix expression ?6?5 * ?4 ?3 ?2 + ?1 - / +a) 19b) 31c) 36d) 635. Given the recursive functionint Func( /* in */ int i,/* in */ int j ){if (i < 11)if (j < 11)return i + j;elsereturn j + Func(i, j - 2);elsereturn i + Func(i - 1, j);}what is the value of the expression Func(12, 15) ?a) 81b) 62c) 19d) 72e) none of the above6. Which one of the following list can use binary search?a) A C E B Db) A B C D Ec) B D A C Fd) E C A B D7. Retrieval from a linked list of length n has running time ( )a) O(1)b) O(lgn)c) O(n)d) O(nlgn)二、填空题(共16分,每空2分)1. If the following function is called with a value of 75 for n, the resulting output is_______【1】_________.void Func( /* in */ int n ){if (n > 0){Func(n / 8);cout << n % 8;}}2. Give the output of the following program. ________【2】__________.template <class List_entry>void print(List_entry &x){cout<<x<<" ";}void main( ){List<int> mylist;for(int i=0;i<5;i++)mylist.insert(i,i);cout<<"Your list have "<<mylist.size()<<" elements:"<<endl;mylist.remove(0,i);mylist.remove(2,i);mylist.insert(i,i);mylist.traverse(print);mylist.clear( );for(i=1;i<3;i++)mylist.insert(i, i);mylist.traverse(print);}3. Read the following program and fill the blank to complete the method.template <class Node_entry>struct Node {// data membersNode_entry entry;Node<Node_entry> *next;Node<Node_entry> *back;// constructorsNode( );Node(Node_entry item, Node<Node_entry> *link_back = NULL, Node<Node_entry>*link_next = NULL);};template <class List_entry>void List<List_entry> :: set_position(int position) const/* Pre: position is a valid position in the List : 0 <=position < count .Post: The current Node pointer references the Node at position . */{if (current_position <= position)for ( ; current_position != position; current_position++)【3】;elsefor ( ; current_position != position; 【4】)current = current->back;}4. Read the following program and fill the blank to complete the method.Error_code recursive_binary_2(const Ordered_list &the_list, const Key &target, int bottom, inttop, int &position)/* Pre: The indices bottom to top define the range in the list to search for the target .Post: If a Record in the range from bottom to top in the list has key equal totarget , then position locates one such entry, and a code of success is returned. Otherwise,not_present is returned, and position is undefined.Uses: recursive_binary_2, together with methods from the classes Ordered_list and Record .*/{Record data;if (bottom <= top) {int mid = 【5】;the_list.retrieve (mid, data);if (data == target) {【6】;return success;}else if (data < target)return recursive_binary_2(the_list, target, 【7】, top, position);elsereturn recursive_binary_2(the_list, target, bottom, 【8】, position);}else return not_present;}三、编程题(共63分)1.(14分)The size of array A is n.If the original array A is (e0, e1, …, e n-2, e n-1).After calling the function inverse, the array A is (e n-1, e n-2, …, e1, e0).Implement the function template:Template <class Type> void inverse( Type A[ ], int n);2.(10分)Write function remove for the implementation of doubly linked list that uses the set_position function.Error_code List<List_entry> :: remove(int position, List_entry &x)3.(16分)Write the following overload operator for stacks:1)bool Stack::operator == (const Stack & s);(8分)2)bool Stack::operator += (const Stack & s);(8分)// pushes the contents of the given stack onto this stack;4.(10分)Write the following function temple:Template <class T> void reverse(Queue <T> & q);// reverses the contents of the given queue;5.(13分)Ackermann’s function is defined as follows,A(0, n) = n+1 for n≥0A(m, 0) = A(m-1, 1) for m>0A(m, n) = A(m-1, A(m, n-1)) for m>0 and n>01)Write a recursive function to calculate Ackermann’s function. (6分)2)Draw the recursion tree of A(2, 1). (7分)数据结构期中考卷参考答案一、单项选择题(3×7=21)1. c2. a3. e4. b5. a6. b7. c二、填空题(2×8=16)【1】113【2】Your list have 5 elements:1 2 4 3【3】current = current->next【4】current_position--【5】(bottom + top)/2【6】position = mid【7】mid + 1【8】mid – 1三、编程题(14+16+10+23=63)1.template<class Type> void inverse ( Type A[ ], int n ) {Type tmp;for ( int i = 0; i <= ( n-1 ) / 2; i++ ){tmp = A[i]; A[i] = A[n-i-1]; A[n-i-1] = tmp;}}2.Error_code List<List_entry> :: remove(int position, List_entry &x) {if (position < 0 || position >= count)return range_error;Node<List_entry> *previous, *following;if (position > 0) {set_position(position - 1);previous = current;following = previous->next;previous->next=following->next;if(following->next)following->next->back=previous;}else{following = head;head = head->next;if(head)head->back=NULL;//should be addedcurrent_position = 0;current = head;}delete following;count--;return success;}3.1)bool Stack::operator==(const Stack &s){Stack s1=s, s2=*this;while (!s1.empty( ))if (s1.top( )!= s2.top( )) return false;else { s1.pop( ); s2.pop( );}}2)bool Stack:: operator+=(const Stack &s){Stack ss=s, s2;while (!ss.empty( )){s2.push(ss.top( ));ss.top( );}while (!s2.empty( )){push(s2.top( ));s2.pop( );}}4.Template <class T> void reverse (Queue<T> & q){Stack<T> s ; T data;while ( !q.empty( )){ q.retrieve(data );s.push( data);q.serve( );}while (!s.empty( )){q.append(s.top( ));s.pop( );}}5.1) int akm ( int m, int n ) {if ( m == 0 ) return n+1; // m == 0else if ( n == 0 ) return akm ( m-1, 1 ); // m > 0, n == 0else return akm ( m-1, akm ( m, n-1 ) ); // m > 0, n > 0 }2)v = 2。

2003数据结构英文试卷

2003数据结构英文试卷

2003 Data Structure Test (120 minutes) Class: Student Number: Name:1.Single-Choice(20 points)(1) The Linked List is designed for conveniently b data item.a. gettingb. insertingc. findingd.locating(2) Assume a sequence list as 1,2,3,4,5,6 passes a stack, an impossible output sequence listIs c .a. 2,4,3,5,1,6b.3,2,5,6,4,1c.1,5,4,6,2,3d.4,5,3,6,2,1(3) A queue is a structure not implementing b .a. first-in/first-outb. first-in/last-outc. last-in/last-outd. first-come/first-serve(4) Removing the data item at index i from a sequential list with n items, d items needto be shifted left one position.a. n-ib. n-i+1c. id. n-i-1(5) There is an algorithm with inserting an item to a ordered SeqList and still keeping theSeqList ordered. The computational efficiency of this inserting algorithm is c .a. O(log2n)b. O(1)c. O(n)d.(n2)(6) The addresses which store Linked List d .a. must be sequentialb. must be partly sequentialc. must be no sequentiald. can be sequential or discontiguous(7) According the definition of Binary Tree, there will be b different Binary Treeswith 5 nodes.a. 6b. 5c. 4d. 3(8) In the following 4 Binary Trees, c is not the complete Binary Tree.a b c d(9) A Binary Tree will have a nodes on its level i at most.a.2ib. 2ic.2i+1d.2i-1(10) If the Binary Tree T2 is transformed from the Tree T1, then the postorder of T1 is theb of T2.a. preorderb. inorderc. postorderd. level order(11) In the following sorting algorithm, c is an unstable algorithm.a. the insertion sortb. the bubble sortc. quicksortd. mergesort(12) Assume there is a ordered list consisting of 100 data items, using binary search to find aspecial item, the maximum comparisons is d .a. 25b.1c. 10d.7(13) The result from scanning a Binary Search Tree in inorder traversal is in c order.a. descending or ascendingb. descendingc. ascendingd. out of order(14) The d case is worst for quicksort.a. the data which will be sorted is too larger.b. there are many same item in the data which will be sorted .c. the data will be sorted is out of orderd. the data will be sorted is already in a sequential order.(15) In a Binary Tree with n nodes, there is a non-empty pointers.a. n-1b. n+1c. 2n-1d.2n+1(16) In a undirected graph with n vertexs, the maximum edges is b .a. n(n+1)/2b. n(n-1)/2c. n(n-1)d.n2(17) The priority queue is a structure implementing c .a. inserting item only at the rear of the priority queue.b. inserting item only at the front of the priority queue.c. deleting item according to the priority of the item.d. first in/first out(18) The output from scanning a minimum heap with level traversal algorithm c .a. must be an ascending sequence.b. must be descending sequencec. must have a minimum item at the head position.d. must have a minimum item at the rear position.(19) Assume the preorder of T is ABEGFCDH, the inorder of T is EGBFADHC, then thepostorder of T will be a .a. GEFBHDCAb. EGFBDHCAc. GEFBDHCAd. GEBFDHCA(20) When a recursive algorithm is transformed into a no recursive algorithm, a structureb is generally used.a. SeqListb. Stackc. Queued. Binary Tree2. Please convert the following infix expression (a*(b+c))+(b/d-e)*a into postfix expression,in the converting process, please draw the change of operator stack and the change of the output. (10 points)3. Assume a list is {xal, wan, wil, zol, yo, xul, yum, wen, wim, zi, xem, zom}, please insert these items to an empty Binary Search Tree and then construct the AVL tree. Please draw the whole processes including inserting an item, or rotate nodes to restore height balance.(10 points)4. Assume a list is {48,35,64,92,77,13, 29,44}, firstly insert these items to an empty complete Binary Tree according to the sequence one by one, then please heapify the complete Binary Tree and implement the heap sort. Please draw the whole heapigying process and sorting process. (10 points)5. For the following directed graph, give the adjacency matrix and adjacency list. Then according your adjacency list, please scan the graph using the depth-first search and the breadth-first search and give the corresponding result. (10 points)6. Assume a list is 35,25,47,13,66,41,22,57, please sorting the list with quicksort algorithm. Please write every sorting pass result (no programming).(10 points)7. Assume keys={32,13,49,55,22,39,20}, Hash function is h(key)=key%7. The linear probe open addressing is used to resolve collisions. Please try to calculate the value of Hash for each key and give the final hash table. (10 points)8. Programming (All methods have been declared in textbook can be used directly, or you can rewrite them if they are not same in your answer) (20 points)(1) Assume there are two ascending ordered lists L1 and L2, please merge L1 and L2 into a new list L3. There will be no duplicate items in L3. Then please reverse the L3 into a descending ordered list.(10 points)(2) Please give the complete declaration of Queue in circle model, then write the insert algorithm and delete algorithm. (10 points)。

c语言英文试卷

c语言英文试卷

c语言英文试卷C语言英文试卷的主要内容包括:基础知识、数据结构与算法、操作系统、网络编程等方面。

以下是一些建议的英文试题:1. Choose the correct answer:Which of the following is NOT a basic data type in C language?A. intB. floatC. stringD. character2. Fill in the blank:The prototype of the function `void swap(int *a, int *b)` is______.3. Write the correct syntax for declaring a 2D array of size 3x4 and initializing it with default values.4. Choose the correct answer:Which of the following is the correct syntax for calling a function na med `sum` that takes two integers as arguments and returns an integer?A. int sum(int a, int b);B. int sum(int, int);C. int sum(a, b);D. int sum(int b, int a);5. Fill in the blank:The return statement in C language is______.6. Write a C program to find the factorial of a given number.7. Write a C program to sort an array of 10 elements using bubble s ort.8. Choose the correct answer:Which of the following is the correct way to declare a function with a pointer parameter?A. void fun(int *p);B. void fun(int &p);C. void fun(int p);D. void fun(int *&p);9. Fill in the blank:In the following code, the purpose of the `malloc` function is to allo cate______.10. Write a C program to demonstrate the use of file I/O operations.11. Write a C program to implement a simple dynamic memory alloc ation using `malloc` and `free`.12. Choose the correct answer:Which of the following is NOT a valid operator in C language?A. %B. &C. |D. <<13. Fill in the blank:The precedence of the following arithmetic operators is______.14. Write a C program to find the sum of all even numbers from 1 to 100.15. Write a C program to implement a function that takes a string as input and reverses it.Remember to provide solutions for each problem, and use appropriate English vocabulary and grammar. This will help you practice your C lan guage programming skills and prepare for an English-based exam or interv iew.。

数据结构C语言版期末考试试题(有答案)精选全文

数据结构C语言版期末考试试题(有答案)精选全文

可编辑修改精选全文完整版“数据结构”期末考试试题一、单选题(每小题2分,共12分)1.在一个单链表HL中,若要向表头插入一个由指针p指向的结点,则执行( B)。

A. HL=ps p一>next=HLB. p一>next=HL;HL=pC. p一>next=Hl;p=HL;D. p一>next=HL一>next;HL一>next=p;2.n个顶点的强连通图中至少含有(B)。

A.n—l条有向边B.n条有向边C.n(n—1)/2条有向边D.n(n一1)条有向边3.从一棵二叉搜索树中查找一个元素时,其时间复杂度大致为( C )。

A.O(1)B.O(n)C.O(1Ogzn)D.O(n2)4.由权值分别为3,8,6,2,5的叶子结点生成一棵哈夫曼树,它的带权路径长度为( D )。

A.24 B.48C. 72 D. 535.当一个作为实际传递的对象占用的存储空间较大并可能需要修改时,应最好把它说明为(B)参数,以节省参数值的传输时间和存储参数的空间。

A.整形B.引用型C.指针型D.常值引用型·6.向一个长度为n的顺序表中插人一个新元素的平均时间复杂度为( A )。

A.O(n) B.O(1)C.O(n2) D.O(10g2n)二、填空题(每空1分,共28分)1.数据的存储结构被分为顺序结构链接结构索引结构散列结构四种。

2.在广义表的存储结构中,单元素结点与表元素结点有一个域对应不同,各自分别为值域和子表指针域。

3.——中缀表达式 3十x*(2.4/5—6)所对应的后缀表达式为————。

4.在一棵高度为h的3叉树中,最多含有—(3h一1)/2—结点。

5.假定一棵二叉树的结点数为18,则它的最小深度为—5—,最大深度为—18—·6.在一棵二叉搜索树中,每个分支结点的左子树上所有结点的值一定—小于—该结点的值,右子树上所有结点的值一定—大于—该结点的值。

7.当向一个小根堆插入一个具有最小值的元素时,该元素需要逐层—向上—调整,直到被调整到—堆顶—位置为止。

数据结构样卷3(英文)

数据结构样卷3(英文)

重庆大学 《数据结构》 课程样卷 3开课学院: 计算机学院 课程号: 18001035 考试日期:考试方式:考试时间: 120 分钟一、 Single choice1. Merge two ordered list, both of them contain n elements, the least timesof comparison is ( ).A. nB. 2n-1C. 2nD. n-12. Sequential stored linear list with the length of 1000, if we insertan element into any position, the possibility is equal, when we insert a new element, the average number of removing elements is ( ). A. 1000 B. 1001 C. 500 D. 4993. Assume that the initial status of stack S and queue Q are both NULL,push elements e1,e2,e3,e4,e5,e6 into the stack S one by one, an element pops from stack, then enter into queue Q. If the sequence which the six elements in the dequeue is e2,e4,e6,e5,e3,e1, the capacity of stack S is at least ( ).A. 6B. 4C. 3D. 24. Two-dimensional array A [10 .. 20,5 .. 10] stores in line sequence,each element occupies 4 storage location, and the memory address of A[10,5] is 1000, then the address of A[20,9] is ( ). A. 1212 B. 1256 C. 1368 D. 13645. A tree with degree 3, it has 2 nodes with the degree 3, one node withthe degree 2, and 2 nodes with the degree 1, so the number of nodes with degree 0 is ( ).A. 4.B. 5.C. 6.D. 76. The inorder sequence of a binary tree is ABCDEFG, and its postordersequence is BDCAFGE, so its pre-order sequence is ( ) A. EGFACDB B. EACBDGF C. EAGCFBD D. EGAFCDB7. A Huffman tree with n leaf nodes, its total number of nodes is ( )A. n-1B. n+1C. 2n-1D. 2n+18. In an adjacency list of undirected graph with n vertexes and e edges,the number of edge node is ( ).A. nB. neC. eD. 2e9. The degree (sum of in-degree and out-degree) of a directed graph isk1, and the number of out-degree is k2. Therefore, in its adjacency list, the number of edge nodes in this singly linked list is ( ). A. k1 B. k2 C. k1-k2 D. k1+k210. If the graph has n vertexes is a circle, so it has ( ) spanning tree.A. nB. 2nC. n-1D.n+111. When look up a sequential list with the length 3, the possibility thatwe find the first element is 1/2, and the possibility that we find the second element is 1/3, the possibility that we find the third element is 1/6, so the average searching length to search any element (find it successfully and the sentry is at the end of the list) is ( ) A. 5/3 B.2 C. 7/3 D.4/312. There is an ordered list {3,5,7,8,11,15,17,22,23,27,29,33}, by binarysearch to search 27, so the number of comparison is ( ) A. 2 B. 3 C. 4 D. 513. Sort the following keyword sequences by using Quicksort, and theslowest one is ( )A. 19,23,3,15,7,21,28B. 23,21,28,15,19,3,7C. 19,7,15,28,23,21,3D. 3,7,15,19,21,23,28 14. Heapsort needs additional storage complexity is ( )A. O(n)B. O(nlog 2n)C. O(n 2) D. O(1)15. If we sort an array within the time complexity of O(nlog2n), needingsort it stably, the way that we can choose is ( )A. Merge sortB. Direct insertion sortC. Heap sortD. Quicksort二、 Fill the blanks1.Assume that the structure of the nodes in doubly circular linked list is (data,llink,rlink), without a head node in the list, if we want命题人:组题人:审题人:命题时间: 教务处制学院 专业、班 年级 学号 姓名公平竞争、诚实守信、严肃考纪、拒绝作弊封线密to insert the node which pointer s points after the node pointer ppoints, then execute as the following statements:; ; ___ _; ;2.Both stack and queue are _______linear structure.3.The four leaf nodes with the weight 9,2,5,7 form a Huffman tree, itsweighted path length is ________.4.In order to ensure that an undirected graph with six vertexes isconnected, need at least ______ edges.5.An n-vertex directed graph, if the sum of all vertices’ out-degreeis s, then the sum of all vertices’ degree is__ ___.6.The Depth-First traversal of a graph is similar to the binarytree_______ traversal; the Breadth-first graph traversal algorithmis similar to the binary tree ______traversal.7. A connected graph with n vertexes and e edges has ____ edges of itsspanning tree.8.The time complexity of binary searching is _____; if there are 100elements, the maximum number of comparisons by binary searching is____.9.Sort n elements by merge sort, the requiring auxiliary space is _____.10.Sort a linear list with 8 elements by Quicksort, at the best, thecomparison time is ______.三、 Application1. Begin from the vertex A, seek the minimum spanning tree by using Primalgorithms2. The following is AOE network:(1) How much time does it take to complete the whole project?(2) Find out all of the critical path.(9 points)3. Assume that a set of keywords is {1,12,5,8,3,10,7,13,97},tryto complete the following questions:(9 points)(1) Choose the keywords in sequence to build a binary sort tree Bt;(2) Draw the structure of the tree after deleting node “12”from thebinary tree Bt.4. The keyword sequence is {503,87,512,61,908,170,897,275,653,462}, usingradix sorting method to sort them in ascending order, try to write every trip results of sort. (9 points)四、 Algorithm1.The following algorithm execute on a singly linked list without headnode, try to analyze and write its function.(5 points)void function(LinkNode *head){LinkNode *p,*q,*r;p=head;q=p->next;while(q!=NULL){r=q->next;q->next=p;p=q;q=r;}head->next=NULL;head=p;}2.Design an algorithm to divide a singly linked list ‘A’ with a headpointer ‘a’ into two singly linked list ‘A’ and ‘B’, whose head pointers are ‘a’and ‘b’, respectively. On the condition that linked list A has all elements of odd serial number in the previous linked listA and linked listB has all elements of even serial number in the previouslinked list A, in addition, the relative order of the original linked list are maintained.(7 points)3. The type of binary tree is defined as follows:typedef struct BiTNode {char data;struct BiTNode *lchild,*rchild;}BiTNode, *BiTree;Please design an algorithm to count how many leaf nodes the binary tree have. (8 points)。

完整word版数据结构C语言版期末考试试题有答案

完整word版数据结构C语言版期末考试试题有答案

the principle of simplified EIA of construction projects in the region. In terms of land, linked to the implementation of urban and rural construction land increase and decrease, replacement indicators for priority areas project. Charges, into the projects of water; electricity, administrative chargeand preferential policies. In the area of taxation, and settled in areas of industry and its production compan% within 5 years after the completion of fiscal incentives to enterprises・ In terms of financing, integration of land, tax, financial and other resources, and con struct Government credit + busi ness credit credit system, establishment of marketizatio n, commercialization and modernization of the investment and financing platform; effective Bank・enterprise docking, encourages private capital into the Park, to raise industry development fund・ 5, optimize the environment and service industries. To create policy lowlands, Highlands, integrity of service land, development land as the goal, to optimize the area under development environment・ All administrative law enforcement departments to appoint a full-time personnel stationed in areas dedicated to coordinating and solving problems associated with businesses in this sector. When there are substantial issues, sector leaders arranged to personally intervene, in-person, in-person push tangible area building a green light, easy line・ To further reduce and standardize administrative examina廿on and approval items, simplify examination and approval links, improve efficiency; according to the ・..Since the educational practice of the mass line of the party, himself seriously in the education,practical control central eight rules and opposing he four winds and practicing hree Suns, and check the spirit of Jiao Yulu, ideology, solicit opinions based on outstanding problems checked swing, careful analysis and reflection・ Will now check report is as follows: first, adherence to the party's political discipline, eight in the central provision, change the style of the basic situation of 1, in compliance with the party's political disciplines. Conscientiously abide by the party's political discipline, abide by the Constitution and the rules and regulations of the party, in the political, ideological and maintain highly consistent with the CPC Central Committee on the action, there is no violation of the party's political discipline problems. 2, in the implementation of the central authorities of the eight provisions・ Improving research, improving research methods, but there are less grass-roots units, primary first-hand an in adequate grasp of the problem, which is to be strengthened in the future・ Second, construction, strictly in accordance with the provisions to streamline and improve the quality of meetings of the Conference・ Third, streamlining file briefs, culture involves all aspects of propaganda and ideology, sometimes due to the practical needs of invention notifications, this area needs further“数据结构”期末考试试题一、单选题(每小题2分,共12分)1.在一个单链表HL中,若要向表头插入一个由指针p指向的结点,则执行()oA. HL = ps p 一>next=HLC- p 一〉next=Hl; p=HL;D- p 一〉next=HL —〉next ;HL —〉next = p;2・n个顶点的强连通图中至少含有()oA. n—1条有向边B. n条有向边C.n(n—1) / 2条有向边D.n(n — 1)条有向边3.从一棵二叉搜索树中查找一个元素时,其时间复杂度大致为()。

数据结构例题(英文版)

数据结构例题(英文版)

I Single Choice(10 points)1. ( )For the following program fragment the running time(Big-Oh) is .i = 0;s = 0;while(s <( 5*n*n + 2)){ i++;s = s + i;}a. O(n)b. O(n2)c. O(n1/2)d. O(n3)2. ( )Which is non-linear data structure_____.a. queueb.stackc. treed. sequence list3.( )The worst-time for removing an element from a sequence list (Big-Oh) is .a. O(1)b. O(n)c. O(n2)d. O(n3)4.( )In a circular queue we can distinguish(区分) empty queues from full queues by .a. using a gap in the arrayb. incrementing queue positions by 2 instead of 1c.keeping a count of the number of elementsd. a and c5.( )A recursive function can cause an infinite sequence of function calls if .a.the problem size is halved at each stepb.the termination condition is missingc.no useful incremental computation is done in each stepd.the problem size is positive6.( )The full binary tree with height 4 has nodes.a. 15b. 16c.31d.327. ( )Searching in an unsorted list can be made faster by using .a.binary searchb. a sentinel(哨兵)at the end of the listc.linked list to store the elementsd. a and c8.()Suppose there are 3 edges in an undirected graph G, If we represent graph G with a adjacency matrix, How many “1”s are there in the matrix?a. 3b. 6c. 1d. 99. ( ) Construct a Huffman tree by four leaf whose weights are 9, 2, 5, 7 respectively. The weighted path length is___________.a. 29b. 37c. 46d.4410. Consider the following weighted graph.Consider Dijkstra’s algorithm on this graph to find the shortest paths with s as a starting vertex. Which are the first four vertices extracted from the priority queue by the algorithm (listed in the order they are extracted) ?a. s, y, t, xb. s, y, x, zc. s, t, y, xd. s, y, x, tFig. 111. Here is an array of ten integers:5 3 8 9 1 7 0 26 4Suppose we partition this array using quicksort's partition function and using 5 for the pivot. Which shows the array after partition finishes:a. 5 3 4 2 1 0 7 9 6 8b. 0 3 4 2 1 5 7 9 6 8c. 3 1 0 2 4 5 8 9 6 7d. 3 1 0 2 4 5 8 9 7 6e. None of the aboveII Fill in Blank (10 points)1. For the following program fragment the running time(Big-Oh) is .for ( int i = 0; i < n; i++ )for ( int j = 0; j < =i; j++)s; //s为某种基本操作2. We store a 4×4 symmetric matrix A into an array B with row major order, Store the lower triangle only. the index of element a[2][3] in B is .3.We can use 3 vector type to store value and of non-zero elements in a sparse matrix.4. A______________ is a list where removal and addition occur at the same end . Frequently knowna LIFO (Last-In-First-Out) structure.5.T( n ) = 2T( n/2 )+ cn, T(n) = T( n-1)+cn, T( n ) = O(___________)6. There is a binary tree whose elements are characters. Preorder list of the binary tree is “ABECDFGHIJ” and inorder list of the binary tree is “EBCDAFHIGJ”. Postorder traversal sequence of the binary tree is .7.There are leaf nodes in a full binary tree with n nodes.8.When the input has been sorted ,the running time of insertion sort(Big-Oh) is .9.We sort the sequence(43,02,80,48,26,57,15,73,21,24,66)with shell sort for increment 3, the result is ______ _ .10、In a circular queue, “front” and “rear” are the front pointer and rear pointer respectively. Queue size is “maxsize”. When insert an element in the queue, rear = _________11. A ____________________________________________ is an example of a search tree which is multiway (allows more than two children).12. A tree in which every node is no smaller than its children is termed______________________.III Application of Algorithms(35 points)1.Graph G shown in Fig 2 is a directed graph, please describe G with adjacency matrix and write the orders of breadth first traversal and depth first traversal.Fig.22.The sequence of input keys is shown below:19,1,23,14,55,20,84,27,68,11,10,17A fixed table size of 19 and a hash function H(key)=key%13,with linear probing(线性探测), fill the table below and compute the average length of successful search.3. Show the results of inserting 53,17,78,09,45,65,87 each , one at a time, in a initially empty max heap(大根堆)4. write the sequence of preorder,postorder traversals and add inorder threads in the tree.Fig. 35. Build a Huffman tree and determine Huffman code when the probability distribution(概率分布) over the 8 alphabets ( c1, c2, c3, c4, c5, c6, c7, c8 ) is (0.05, 0.25, 0.03, 0.06, 0.10, 0.11, 0.36, 0.046. Graph G shown in Fig 4 is a directed graph, please describe G with adjacency list and write topological ordering.Fig. 4IV Fill in blank of algorithms.(15)1.Here is single source shortest path algorithm Dijkstra. Fill in blank of the algorithm.class Graph {//图的类定义private:float Edge[NumVertices][NumVertices];float dist[NumVertices];//最短路径长度数组int path[NumVertices];//最短路径数组int S[NumVertices];//最短路径顶点集public:void ShortestPath ( int, int );int choose ( int );};void Graph :: ShortestPath ( int n, int v ){//在具有n 个顶点的带权有向图中, 各边上权值由Edge[i][j]给出。

数据结构英文试题(修改)

数据结构英文试题(修改)

200X年试题选择题(1)Suppose 1,2,3,4 is the order which these elements push onto a stack. The sequence obtained is(B)A.4.1.2.3B.3.2.4.1C.3.4.1.2D.4.3.1.2(2)Suppose that a linear list contains n=31 nodes, the binary search is applied to the list, the maximum times in searching is (B)A 4B 5C 25-1D 24-1(3)In the following sorting algorithms, which is unstable(A)A Selection sortB Merge sortC Bubble sortD Insertion sort(4)Bubble sort is used for n nodes, the minimum number of comparisons is (A)A n-1B nC n(n-1/2)D n(n+1)/2(5)How many binary trees in different forms can at most be built by three nodes?(B)A 4B 5C 6D 7填空题.(1)The stack takes on character of ___________后进先出____________________(2)The postfix expression is ‘abcdef*/-*+’. Its infix expression is_a+b[c-d/(e*f)]____(3)The advantage of circular queues is _______克服队满溢出_________.(4)If the depth of full binary tree is k, then the number of nodes in the tree at least_2^k+1-1__ (5)The selection sort is used to sort n nodes, the number of its comparisons is __n(n-1)/2____ 三.(1) Write a function Deletion in C for linear list. (5 points)int sq_elete(list,p_n,i)int list[];/*形参数组可不指定大小*/int *p_n,i;{int j;if(i<0||i>=*p_n) return(1);for(j=i+1,j<*p_n;j++) list[j-1]=list[j];(*p_n)--;return(0);}(2)Write a function Pop in C for linked stack. (5 points)(3)Write a function in C for binary search. (10 point )int bisect(a,n,v)int a[],v, n;{ int i,j,m;i=0;j=n-1;while(i<=j){ m=(i+j)/2;if(v==a[m])return(m);if(v<a[m]) j=m-1;else i=m+1;}return(-1);}(4)Write some sentences in C which delete the node b in the following figure. (5 point)(附图)(5)Write some sentences in C which insert the node b in the following figure(5pont)(附图)四.(2)Write a function in C of quick sort. (10 point )Position Partition(List *list, Posotion low, Position high){ ListEntry pivot;Position i, lastsmall, pivotpos;Swap(low,(low+high)/2,list);pivot=list->entry[low];pivotpos=low;for(i=low+1; i<=high;i++)if(LT(list->entry[i].key, pivot.key))Swap(++pivotpos, i, list);Swap(low, pivotpos, list);return pivotpos;}(3)Suppose that a hash table contains 5 entries indexed from 0 through 4 and that the following keys are to be mapped into the table.12,19,17,14,10,24,15Hash function h(k)=k mod 5.(a)Determine the hash addresses and resolute collision by chaining.(b)Write a function in C for search by chaining. (10point)void search2(t,k,p,q)NODE *t[ ];int k;NODE *p,*q;{ *p=NULL;*q=t[h(k)];while(*q!=NULL)if ((*q)->key==k) return;else{*p=*q;*q=(*q)->link;}}五.(1)Write a function in C which will inter change all left and right subtrees in binary tree. (10 point)(2)Write a function in C for linked queue.(10 point)void Append(QueueEntry x,Queue *q){if (QueueFull(q))Error(“cannot append an entry to a full queue.”);else{q->count++;q->rear=(q->rear+1)%MAXQUEUE;q->entry[q->rear]=x;}}选择题(1)In a simple linked list with n nodes, the number of pointer fields with NULL Totals(D).A. nB.2C.n/2D.1(2)In the linear lists, two concepts which are the same as each other is(AB)A node B. record C. field D. type of structure(3)In the binary search tree, for any root of subtree, the keys of all nodes in its left subtree is (D) the keys of all nodes in its right subtree.A less thanB equal toC great thanD less than or equal to(4)For general trees, the correct choice is (B)A it may be emptyB at least one nodeC at least two nodesD A.B and C are incorrect(5)The bubble sort is used to n nodes, least number of comparison is(A)A n-1B nC n(n-1)/2D n(n+1)/2填空题(1)A binary tree with n nodes storaged by standard form, there are ___2n__ pointers where _n-1___pointers are used to point to sub-nodes, and _n+1___ pointers are empty.(2)The postfix expression is abc*+de/f*-, then its infix expression is _a+b*c-d/e*f___(3)The basic operations of linear lists are___插入删除访问______(4)The character of stack is__后进先出__________(5)Hash storage faced with two problems of __Hash函数____ and ____冲突___三.(1)Write a function Pop for stack (5point )V oid Pop(StackEntry *item, Stack *s){if(StackEmpty(s))Error;else*item=S->entry[--s->top] ;}(2)Translate the quadratic formula.(a+b*c)↑d↑(e*f/g)-h*iinto postfix form. (10point)(3)Write a function in C which changes the linked list in Figure 1 to another linked list in Figure2.(10point)(附图)(4)(1).(a)By hand, trace through the steps bubble sort will use on the list. The following seven number to be sorted into increasing order.(b)Write a function of bubble sort. (10point)void bubble_sort(a,n)int a[],n;{ int i,j,t;n ;while(n>0){j=0;for(i=0;i<n;i++)if(a[i]>a[i+1]){t=a[i];a[i]=a[i+1];a[i+1]=t;j=i;}n=j;}}(2)By hand, sort the list 46.26.22.68.48.42.36.84.66 using selection sort.Write a function of selection sort.(10point)void insertion_sort(a, n)int a[ ];int n;{ int i, j;int t;for(i=1;i<n;i++){t=a[i];for(j=i-1;j>=0&&t<a[j];j--)a[j+1]=a[j];a[j+1]=t;}}(3).Suppose that a hash table contains 11 entries from 0 through 10 and that the following keys are to be mapped into the table.(32,75,63,48,94,25,36,18,70)Hash function h(k)=k mod 11(a)Determine the hash addresses and resolute collision by linear probing.(b)Determine the hash addresses and resolute collision by chaining. (10point )(4)For each of the following binary trees, determine the order in which the nodes will be visitedmixed order given by invoking function A(5point)Void A(TreeNode *root, void(*Visit)(TreeEntry x) ){If(root){Visit(root->entry)’B(root->left, Visit);B(root->right, Visit);}}void B(TreeNode *root, void(*Visit)(TreeEbtry x)){If(root){A(root->left, Visit);Visit(root->entry);A(root->right, Visit);}}五.(2)Insert a new node r taken as the right child of node s and draw a threaded-tree.(a) By hand(b) By some sentences in C (10 point)(a)(b)r->rightchild=s->rightchild; // s的右子女指针或后继线索传给rr->rightthread=s->rightthread;//标志一同传送//ar->leftchild=s;r->leftthread=1; // r为leftchild或为s的前驱线索//bs->rightchild=r;s->rightthread=0; //r成为s的右子女//c。

2016数据结构基础(C语言版)习题及答案(英文版)

2016数据结构基础(C语言版)习题及答案(英文版)

数据结构基础(C语言版)习题及答案(英文版)目录CHAPTER 1 (2)CHAPTER 2 (24)CHAPTER 3 (44)CHAPTER 4 (63)CHAPTER 5 (79)CHAPTER 6 (96)CHAPTER 7 (125)CHAPTER 8 (139)CHAPTER 9 (140)CHAPTER 10 (142)CHAPTER 11 (147)CHAPTER 12 (170)CHAPTER 1Chapter 1, Pages 16-17Problem 1.a This statement is a poorly phrased version of Fermat's last theorem. We know that we can find n > 2 for which ‚the equation holds. Fermat scribbled a note on a text margin indicating that he had found the solution for n = 2. Unfortunately, the proof died with him. Be cause the statement is phrased as a question‚ rather than a clearly defined algorithm, it lacks definiteness.Problem 1.b This statement violates not only the rules of mathematics, but the criterion of effectiveness. We can compute only those things that are feasible, and division by zero is mathematically undefinedPage 17, Exercise 3#include <stdio.h>#include <math.h>#include <string.h>#define TRUE 1#define FALSE 0#define MAX_STRING 100void truth_table(int);int main(){int n;printf("n:(>=0): ");scanf("%d", &n);while (n <= 0){ /*error loop */printf("n:(>=0): ");scanf("%d", &n);}truth_table(n);}void truth_table(int n){/* generate a truth_table by transforming # of permutations into binary */int i,j, div, rem;char string[MAX_STRING];for (i=0; i < pow(2,n); i++){/*number of permutations or rows in the table */ strcpy(string ,"\0");div = i;for (j = n; j > 0; j--){/*number of bits needed for each row*/rem = div%2;div = div/2;if (!rem) strcat(string,"FALSE ");else strcat(string, "TRUE ");}printf("%s\n", string);}}Page 17, Exercise 4#include <stdio.h>int min(int, int);#define TRUE 1#define FALSE 0int main(){int x,y,z;printf("x: "); scanf("%d", &x);printf("y: "); scanf ("%d", &y);printf("z: "); scanf("%d", &z);if (min(x,y) && min(y,z)) {/*x is smallest */printf("%d ", x);if (min(y,z)) printf ("%d %d\n", y,z);else printf("%d%d\n", z, y);}else if (min(y,x) && min(y,z)){ /*y is the smallest */ printf("%d ", y);if (min(x,z)) printf ("%d %d\n", x,z);else printf("%d%d\n", z,x);}elseprintf("%d %d %d\n", z, y, x);}int min(int a, int b) {if (a < b) return TRUE;return FALSE;}Page 17, Exercise 7#include <stdio.h>double iterFact(int);double recurFact(int);int main(){int n;printf("n:(>=0): ");scanf("%d", &n);while (n < 0){ /*error loop */printf("n:(>=0): ");scanf("%d", &n);}printf("%d factorial is %f.\n", n, iterFact(n)); printf("%d factorial is %f.\n", n, recurFact(n)); }double recurFact(int n){ /*recursive version */if ((n==0) || (n==1)) return 1.0;return n*recurFact(n-1);}double iterFact(int n){/* find the factorial, return as a doubleto keep it from overflowing */int i;double answer;if ((n == 0) || (n == 1)) return 1.0;answer = 1.0;for (i = n; i > 1; i--)answer *= i;return answer;}Page 17, Exercise 8#include <stdio.h>int iterFib(int);int recurFib(int);int main(){int n;printf("n:(>=0): ");scanf("%d", &n);while (n < 0){ /*error loop */printf("n:(>=0): ");scanf("%d", &n);}printf("%d Fibonacci is %d.\n", n, iterFib(n)); printf("%d Fibonacci is %d.\n", n, recurFib(n)); }int recurFib(int n){ /*recursive version */if ((n==0) || (n==1)) return 1;return recurFib(n-1) + recurFib(n-2);}int iterFib(int n){/* find the factorial, return as a doubleto keep it from overflowing */int i;int fib, fib1, fib2;if ((n == 0) || (n == 1)) return 1;fib1 = fib2 = 1;for (i = 2; i <=n; i++) {fib = fib1+fib2;fib2 = fib1;fib1 = fib;}return fib;}Page 17, Exercise 9#include <stdio.h>double recurBinom(int, int);double iterBinom(int, int);double recurFact(int n);int main(){int n,m;printf("n:(>=0): ");scanf("%d", &n);while (n < 0){ /*error loop */printf("n:(>=0): ");scanf("%d", &n);}printf("m:(>=0): ");scanf("%d", &m);while (m < 0){ /*error loop */printf("m:(>=0): ");scanf("%d", &m);}printf("n: %d m: %d Recursive Binomial coefficient is %f.\n", n, m, recurBinom(n,m)); printf("n: %d m: %d Iterative Binomial coefficient is %f.\n", n, m, iterBinom(n,m));}double iterBinom(int n, int m){/* defined as n!/(m! - (n-m)!)*/int i;double nFact, mFact, nMinusMFact;if (n == m) return 1;if ((n==0) || (n == 1)) nFact = 1;else {nFact = 1;for (i = n; i > 1; i--)nFact *= i;}if ((m==0) || (m == 1)) mFact = 1;else {mFact = 1;for (i = m; i > 1; i--)mFact *= i;}if ( ((n-m) == 0) || ((n-m) == 1)) nMinusMFact = 1;else {nMinusMFact = 1;for (i = n-m; i > 1; i--)nMinusMFact *= i;}return nFact/(mFact*nMinusMFact);}double recurFact(int n){ /*recursive version */if ((n==0) || (n==1)) return 1.0;return n*recurFact(n-1);}double recurBinom(int n, int m){ /*recursive version */return recurFact(n)/(recurFact(m)*recurFact(n-m));}Page 17, Exercise 11#include#define Tower1 1#define Tower2 2#define Tower3 3void towers_of_hanoi(int, int, int, int);int main(){int n_disks;printf("Number of disks: ");scanf("%d", &n_disks);printf("Disk, source, and destination towers listed below\n");printf("%12s%10s%15s\n", "Disk No", "Source","Destination");towers_of_hanoi(n_disks,Tower1,Tower3,Tower2);}void towers_of_hanoi(int n_disks, int source, int dest, int spare){if (n_disks == 1 )printf("%10d%10d%10d\n", n_disks, source, dest);else {/*move a disk from source to spare*/towers_of_hanoi(n_disks-1,source,spare,dest);printf("%10d%10d%10d\n", n_disks, source, dest);/*move a disk from spare to destination tower*/towers_of_hanoi(n_disks-1,spare,dest,source);}}Page 21, Exercise 1ADT NaturalNumber is objects:an ordered subrange of the integers starting at zero and ending at the maximum integer (INT_MAX) on the computer functions: forall x, y ∈NaturalNumber; TRUE, FALSE ∈Booleanand where +, −, <, and == are the usual integer operationsNaturalNumber Zero( ) ::= 0Boolean IsZero(x) ::= if (x) return FALSEreturn TRUEBoolean Equal(x, y) ::= if (x == y) return TRUEreturn FALSENaturalNumber Successor(x) ::= if (x == INT_MAX) return xreturn x + 1NaturalNumber Add(x, y) ::= if ((x + y) < INT_MAX) return x + y if ((x + y) == INT_MAX) return x + yreturn INT_MAXNaturalNumber Subtract(x, y) ::= if (x < y) return 0return x − yNaturalNumber Predecessor(x) ::= if (x < 0) return ERRORif (x == 0) return 0return x - 1Boolean IsGreater(x, y) := if ((x-y)) < 0) return ERRORif ((x-y)) == 0) return FALSEreturn TRUENaturalNumber mult(x, y) ::= if (x < 0) return ERRORif (y < 0) return ERRORif (y == 1) return xreturn x + mult(x, y-1)NaturalNumber div(x, y) ::= if (x < 0) return ERRORif (y < 0) return ERRORif (y == 0) return ERRORif (y == 1) return 1return x - div(x, y-1)end NaturalNumberPage 21, Exercise 3ADT Set is objects:a subrange of the integers starting at (INT_MIN) and ending at themaximum integer (INT_MAX) on the computer functions: forall x, y ∈Set; TRUE, FALSE ∈Boolean and the Boolean operations defined in Problem 4 are available (not, and, or,...)and where ==, Ø, +, head(s), tail(s) are the usual set operations,where == return TRUE if tw set elements are the same, and TRUE otherwise.Ø is the empty set.+ adds and element to a set.head(s) extracts the first member in the set.tail(s) extracts a list of all other elements in the set. An empty set contains no tail. A set with only one element has the emtpy set has it tail.Set Create(s) ::= ØBoolean IsEmpty(s) ::= if (s ==Ø ) return TRUEreturn FALSEBoolean IsIn(x, s) ::= if (IsEmpty(s)) return FALSEif (x == head(s) return TRUEreturn IsIn(x, Tail(s))Set Insert(x,s) ::= if (IsEmpty(s)) return x + sif (IsIn(a,s)) return sreturn x + sSet Remove(x, s) ::= if (x == head(s)) return tail(s)return Remove(x, tail(s))Set Union(x, s1, s2) ::= if IsEmpty(s1) return s2if IsIn(head(s1), s2)) return Union(x, tail(s1), s2)return head(s1) + Union(x, tail(s1), s2)set Intersection(x, s1,s2) ::= if IsEmpty(s1) return Øif IsIn(head(s1), s2)) return head(s1) + Intersection(x, tail(s1), s2)return Intersection(x, tail(s1), s2)Boolean Difference(s1,s2) ::= if IsEmpty(s1) return Øif IsIn(head(s1), s2)) return Difference(x, tail(s1), s2)return head(s1) + Difference(x, tail(s1), s2)end SetPage 21, Exercise 3ADT Bag is objects:a subrange of the integers starting at (INT_MIN) and ending at themaximum integer (INT_MAX) on the computer functions: forall x, y ∈Bag; TRUE, FALSE ∈Boolean and the Boolean operations defined in Problem 4 are available (not, and, or,...)and where ==, Ø, +, head(s), tail(s) are the usual Bag operations,where == return TRUE if tw set elements are the same, and TRUE otherwise.Ø is the empty Bag.+ adds and element to a Bag.head(s) extracts the first member in the Bag.tail(s) extracts a list of all other elements in the Bag. An empty bag contains no tail. A bag with only one element has the emtpy bag has it tail.Bag Create(b) ::= ØBoolean IsEmpty(b) ::= if (b ==Ø ) return TRUEreturn FALSEBoolean IsIn(x, b) ::= if (IsEmpty(b)) return FALSEif (x == head(b) return TRUEreturn IsIn(x, Tail(b))Bag Insert(x,s) ::= if (IsEmpty(b)) return breturn x + bBag Remove(x, s) ::= if (IsEmpty(b)) return bif (x == head(b)) return tail(b)return Remove(x, tail(b))end bagPage 21, Exercise 4ADT Boolean is objects:TRUE, FALSE ∈Boolean and the Boolean== the usual boolean operation. where == return TRUE if tw set elements are the same, and TRUE otherwise.Boolean not(x) ::= if (x) return TRUE return FALSEBoolean and(x,y) ::= if(not(x)) return FALSEif (not(y)) return FALSEreturn TRUEBoolean or(x, s)::= if(x) return TRUEif (y) return TRUEreturn FALSEBoolean xor(x, s)::= if(and(not(x), not(y))) return FALSEif (and(x, y)) return FALSEreturn TRUEBoolean implies(x, s)::= if (and(x, y)) return TRUEif (and(not(x),not(y))) return TRUEreturn FALSEBoolean equivalent(x, s)::= if(and(not(x), not(y))) return TRUEif (and(x, y)) return TRUEreturn FALSEend SetPage 25, Exercise 1Iterative Factorial Function, SiterFact(I) = 0 Recursive Function: recurFact()Type Name Number of Bytes Parameter(int) n 4 Local Variables(int)(double) ianswer46Return Type (double) 6TOTAL 20 for each recursive callif (n == MAX_SIZE) SrecurFact(I) = (20•MAX_SIZE)Page 21, Exercise 3ADT Set is objects:a subrange of the integers starting at (INT_MIN) and ending at themaximum integer (INT_MAX) on the computer functions: forall x, y ∈Set; TRUE, FALSE ∈Boolean and the Boolean operations defined in Problem 4 are available (not, and, or,...)and where ==, Ø, +, head(s), tail(s) are the usual set operations,where == return TRUE if tw set elements are the same, and TRUE otherwise.Ø is the empty set.+ adds and element to a set.head(s) extracts the first member in the set.tail(s) extracts a list of all other elements in the set. An empty set contains no tail. A set with only one element has the emtpy set has it tail.Set Create(s)::= ØBoolean IsEmpty(s) ::= if (s ==Ø ) return TRUEreturn FALSEBoolean IsIn(x, s)::= if (IsEmpty(s)) return FALSEif (x == head(s) return TRUEreturn IsIn(x, Tail(s))Set Insert(x,s)::= if (IsEmpty(s)) return x + sif (IsIn(a,s)) return sreturn x + sSet Remove(x, s)::= if (x == head(s)) return tail(s)return Remove(x, tail(s))Set Union(x, s1, s2)::= if IsEmpty(s1) return s2if IsIn(head(s1), s2)) return Union(x, tail(s1), s2)return head(s1) + Union(x, tail(s1), s2)set Intersection(x, s1,s2)::= if IsEmpty(s1) returnØif IsIn(head(s1), s2)) return head(s1) + Intersection(x, tail(s1), s2)return Intersection(x, tail(s1), s2)Boolean Difference(s1,s2)::= if IsEmpty(s1) returnØif IsIn(head(s1), s2)) return Difference(x, tail(s1), s2)return head(s1) + Difference(x, tail(s1), s2)end SetPage 21, Exercise 3ADT Bag is objects:a subrange of the integers starting at (INT_MIN) and ending at themaximum integer (INT_MAX) on the computer functions: forall x, y ∈Bag; TRUE, FALSE ∈Boolean and the Boolean operations defined in Problem 4 are available (not, and, or,...)and where ==, Ø, +, head(s), tail(s) are the usual Bag operations,where == return TRUE if tw set elements are the same, and TRUE otherwise.Ø is the empty Bag.+ adds and element to a Bag.head(s) extracts the first member in the Bag.tail(s) extracts a list of all other elements in the Bag. An empty bag contains no tail. A bag with only one element has the emtpy bag has it tail.Bag Create(b)::= ØBoolean IsEmpty(b) ::= if (b ==Ø ) return TRUEreturn FALSEBoolean IsIn(x, b)::= if (IsEmpty(b)) return FALSEif (x == head(b) return TRUEreturn IsIn(x, Tail(b))Bag Insert(x,s)::= if (IsEmpty(b)) return breturn x + bBag Remove(x, s)::= if (IsEmpty(b)) return bif (x == head(b)) return tail(b)return Remove(x, tail(b))end bagPage 32, Exercise 4: PrintMatrixa. Countsvoid Printmatrix(int matrix[][MAX_SIZE], int rows, int cols) {int i,j;int count = 0;for (i = 0; i<rows; i++){count ++; /*for i loop */for (j = 0; j<cols; j++) {printf("%5d",matrix[i][j]);count++; /*for j loop */}count++; /* last time of j */printf("\n");}count++; /* last time of i */printf("Print Count: %d\n", count);}b. Simplified Countsvoid Printmatrix(int matrix[][MAX_SIZE], int rows, int cols) {int i,j;int count = 0;for (i = 0; i<rows; i++){count ++; /*for i loop */for (j = 0; j<cols; j++) {printf("%5d",matrix[i][j]);count++; /*for j loop */}count++; /* last time of j */printf("\n");}count++; /* last time of i */printf("Print Count: %d\n", count);}c. Final Count for 5x5 matrix : 36d. Step Count TableStep Count TableStatement s/e f Total Stepsvoid Printmatrix(int matrix[][MAX_SIZE], int rows, int cols){int i,j;for (i = 0; i<rows; i++){for (j = 0; j<cols; j++)printf("%5d",matrix[i][j]);printf("\n");}} 01101n+1n+1n+1n+1Total 2n+2Page 32, Exercise 5 Multiplicationa. Countsvoid mult(int a[][MAX_SIZE], int b[][MAX_SIZE], int c[][MAX_SIZE]){int i, j,k;int count = 0;for (i = 0; i < MAX_SIZE; i++) {count ++; /*for i loop */for (j = 0; j < MAX_SIZE; j++) {c[i][j] = 0; count++; /* for assignment */count++; /*for j loop */}count++; /* last time of j */for (k=0; k < MAX_SIZE; k++){c[i][j] += (a[i][k] * b[k][j]); count++; /* for assignment */count++; /* for k loop*/}count++; /*last time of k */}count++; /* last time of i */printf("Multiplication Count: %d\n", count);}b. Simplified Countsvoid mult(int a[][MAX_SIZE], int b[][MAX_SIZE], int c[][MAX_SIZE]) {int i, j,k;int count = 0;for (i = 0; i < MAX_SIZE; i++) {for (j = 0; j < MAX_SIZE; j++) {c[i][j] = 0;count+=2;}for (k=0; k < MAX_SIZE; k++){c[i][j] += (a[i][k] * b[k][j]);count+=2;}count+=3;}count++; /* last time of i */printf("Multiplication Count: %d\n", count);}c. Final Count for 5x5 matrix: 119d. Step Count TableStep Count TableStatement s/e f (MAX_S) = MAX_SIZE Total Stepsvoid mult(inta[][MAX_SIZE], int b[][MAX_SIZE],int c[][MAX_SIZE]) {int i, j,k; 0111111MAX_S+1MAX_S·MAX_S + MAX_SMAX_S+1MAX_S·MAX_S + MAX_Sfor (i = 0; i < MAX_SIZE; i++)for (j = 0; j < MAX_SIZE; j++) {c[i][j] = 0;for (k=0; k < MAX_SIZE; k++)c[i][j] +=(a[i][k] *b[k][j]);}} 0111MAX_S·MAX_SMAX_S·MAX_SMAX_S·MAX_S·MAX_S +MAX_S·MAX_S·MAX_sMAX_S·MAX_S·MAX_SMAX_S·MAX_SMAX_SMAX_S·MAX_SMAX_S·MAX_S·MAX_S +MAX_S·MAX_S·MAX_SMAX_S·MAX_S·MAX_STotal : 3·MAX_SIZE3+ 2·MAX_SIZE2+ 2·MAX_SIZE + 1 = O(MAX_SIZE)3Page 32, Exercise 4: Producta. Countsvoid prod(int a[][MAX_SIZE], int b[][MAX_SIZE], int c[][MAX_SIZE], int rowsA, int colsB, int colsA){int i, j,k;int count = 0;for (i = 0; i < rowsA; i++) {count ++; /*for i loop */for (j = 0; j < colsB; j++) {c[i][j] = 0; count++; /* for assignment */count++; /*for j loop */for (k = 0; k < colsA; k++) {count++; /* for k loop*/c[i][j] += (a[i][k] * b[k][j]); count++; /*for assignment */}count++; /*last time of k */}count++; /* last time of j */}count++; /* last time of i */printf("Prod Count: %d\n", count);}b. Simplified Countsvoid prod(int a[][MAX_SIZE], int b[][MAX_SIZE],int c[][MAX_SIZE], int rowsA, int colsB, int colsA){int i, j,k;int count = 0;for (i = 0; i < rowsA; i++) {for (j = 0; j < colsB; j++) {c[i][j] = 0; count++;count+=3;for (k = 0; k < colsA; k++) {count++;c[i][j] += (a[i][k] * b[k][j]);count+=2;}}count+=3;}count++; /* last time of i */printf("Prod Count: %d\n", count);}c. Final Count for 5x5 matrixvoid prod(int a[][MAX_SIZE], int b[][MAX_SIZE], int c[][MAX_SIZE], int rowsA, int colsB, int colsA){int i, j,k;for (i = 0; i < rowsA; i++)for (j = 0; j < colsB; j++) {c[i][j] = 0;for (k = 0; k < colsA; k++)c[i][j] += (a[i][k] * b[k][j]);}}d. Step Count Table : 336Step Count TableStatement s/e f (A = rows A, B =rowsB)Total Stepsvoid prod(int a[][MAX_SIZE], int b[][MAX_SIZE],int c[][MAX_SIZE], int rowsA, int colsB, int colsA){int i, j,k;for (i = 0; i < rowsA; i++)for (j = 0; j < colsB; j++) {c[i][j] = 0;for (k = 0; k < colsA; k++)c[i][j] += (a[i][k] * b[k][j]);}} 0111111111A+1A•B+ B+1A•BA•BA•B•A + A•B+ A+1A•B•A + A•B+ AA•BAA+1A•B+ B+1A•BA•B•A +A•B+ A+1A•B•A +A•B+ ATotal : 2A•B•A + 3A•B + 2A + B + 3Page 32, Exercise 4a. Countsvoid transpose(int a[][MAX_SIZE]){int i, j;int temp;int count = 0;for (i = 0; i & lt; MAX_SIZE-1; i++) {count ++; /*for i loop */for (j = i+1; j < MAX_SIZE; j++) {count ++; /*for j loop */SWAP(a[i][j],a[j][i],temp); count+=3; /*for swap */}count++; /* last timne of j */}count++; /* last time of i */printf("Transpose Count: %d\n", count);}b. Simplified Countsvoid transpose(int a[][MAX_SIZE]){int i, j;int temp;int count = 0;for (i = 0; i < MAX_SIZE-1; i++) {for (j = i+1; j < MAX_SIZE; j++) {count ++; /*for j loop */SWAP(a[i][j],a[j][i],temp); count+=3; /*for swap */}count+=2;}count++; /* last time of i */printf("Transpose Count: %d\n", count);}c. Final Count for 5x5 matrix : 49d. Step Count TableStep Count TableStatement s/ef Total Stepsvoid transpose(inta[][MAX_SIZE]){int i, j;int temp;for (i = 0; i =< MAX_SIZE-1; i++)for (j = i+1; j < MAX_SIZE; j++)SWAP(a[i][j],a[j][i], temp);} 01131111MAX_SMAX_S(MAX_S-1)+MAX_SMAX_S(MAX_S-1)1MAX_SMAX_S•MAX_S-1 +MAX_S3(MAX_S(MAX_S-1))Total : 4MAX_SIZE•MAX_S-1 + 2MAX_SIZEPage 32, Exercise 4a. Countsvoid transpose(int a[][MAX_SIZE]){int i, j;int temp;int count = 0;for (i = 0; i & lt; MAX_SIZE-1; i++) {count ++; /*for i loop */for (j = i+1; j < MAX_SIZE; j++) {count ++; /*for j loop */SWAP(a[i][j],a[j][i],temp); count+=3; /*for swap */}count++; /* last timne of j */}count++; /* last time of i */printf("Transpose Count: %d\n", count);}b. Simplified Countsvoid transpose(int a[][MAX_SIZE]){int i, j;int temp;int count = 0;for (i = 0; i < MAX_SIZE-1; i++) {for (j = i+1; j < MAX_SIZE; j++) {count ++; /*for j loop */SWAP(a[i][j],a[j][i],temp); count+=3; /*for swap */}count+=2;}count++; /* last time of i */printf("Transpose Count: %d\n", count);}c. Final Count for 5x5 matrix : 49d. Step Count TableStep Count TableStatement s/ef Total Stepsvoid transpose(inta[][MAX_SIZE]){int i, j;int temp;for (i = 0; i =< MAX_SIZE-1; i++)for (j = i+1; j < MAX_SIZE; j++)SWAP(a[i][j],a[j][i], temp);} 01131111MAX_SMAX_S(MAX_S-1)+MAX_SMAX_S(MAX_S-1)1MAX_SMAX_S•MAX_S-1 +MAX_S3(MAX_S(MAX_S-1))Total : 4MAX_SIZE•MAX_S-1 + 2MAX_SIZEPage 40, Exercise 11. Show that the following statements are correct:(a) 5n2− 6n = θ(n2) Sincen 2 is the leading exponent this is correct.(b) n! = O(n n) n! is the leading exponent and its time is anon-deterministic polynomial, so this is correct.(c) n2+ n log n = θ(n2 ) n2 is the leading exponent.(f) n2n + 6 . 2n = θ(n2n) n2n is the leading exponent.(g) n2 + 103n2 = θ(n3) Since 103 is a constant and the time is based onthe leading exponent for the variable, this should be n2.(h) 6n3 / (logn+ 1) = O(n3) n3 is the leading exponent.(i) n1.001 + n logn = θ(n1.001 ) This is debatable because n lognactuallygrows at a faster rate than n raised to 1.0001 except for n < 2.(j) n k + n + n k logn = θ(n k logn) for all k ≥ 1. n k logngrows at a fasterrate.(k) 10n3 + 15n4 +100n22n = O(n22n) n22n is the leading exponent.Page 40, Exercise 2Show that the following statements are incorrect:(a) 10n2 + 9 = O(n). The leading exponent is n2 so the correct answer is O n2)(b) n2 logn = θ(n2). The leading exponent is n2 lognso the time is θ(n2logn). <(c) n2 / logn = θ(n2 ). The leading expoonent is n2 / lognso the time isθ( n2 / log n).(d) n32n+ 6n23n= O(n22n). It doesn't make much difference because either way this time is a non-deterministic polynomial. The time should be O( n n).(e) 3n n = O(2n ). The time should be O( n n).Page 41, Exercise 3Page 41, Exercise 4Page 41, Exercise 5Program 1.19 prints out a 2-dimensional array. The outerloop iterates n times as does the inner loop. The time is n•n; therefore, the worst case time is O(n2 ).Page 41, Exercise 6Program 1.19 multiplies a 2-dimensional array. It requires 3-nested loops each iteratint n times. The time is n•n•n; therefore the worst case time is O(n3). Strassen's Matrix Multiplication method reduces the complexity to : O(n2.76).Page 41, Exercise 7a: O(n2)b : 20n+ 4The answer is obvious because 20•20 = 2020. (a) will exceed b at n>20. CHAPTER 2Page 58, Exercise 1#include <stdio.h>#include <stdlib.h>int** make2dArray(int, int);#define MALLOC(p,s) \if (!((p) = malloc(s))) {\fprintf(stderr, "Insufficient memory"); \exit(EXIT_FAILURE); \}int main(){int i,j;int **myArray;myArray = make2dArray(5,10);myArray[2][4]=6;for (i = 0; i<5; i++){for (j = 0; j < 10; j++){/*myArray[i][j] =0;*/printf("%d ", myArray[i][j]);}printf("\n");}}int** make2dArray(int rows, int cols){/*create a 2-d array rows x cols */int **x, i;MALLOC(x,rows*sizeof(*x)); /*get memory for row pointers*/for(i = 0; i < rows; i++){MALLOC(x[i], cols * sizeof(**x)); /*get memory for col pointers*/ *x[i]=0;}return x;}Page 64, Exercise 1#include <stdio.h>#include <string.h>typedef struct {int month;int day;int year;} date;typedef struct {;}noMarriage;typedef struct { date dom, dodivorce;}divorce;typedef struct {date dom, dodeath;}widow;typedef struct {enum tagField {single, married, widowed, divorced} status;union {noMarriage nom;date dom;divorce divorceStuff;widow widowStuff;} u;} maritalStatus;typedef struct {char name[10];int age;float salary;date dob;maritalStatus ms;}humanBeing;void printPerson(humanBeing);int main(){humanBeing p1;p1.dob.month = 5;p1.dob.day = 16;p1.dob.year = 1978;strcpy(, "Fiona");p1.salary = 1.00;p1.ms.status = married;p1.ms.u.dom.month = 10;p1.ms.u.dom.day = 31;p1.ms.u.dom.year = 1999;printPerson(p1);}void printPerson(humanBeing p){/*print out the information on a person */printf("Name: %s\n", );printf("DOB: %d/%d/%d\n", p.dob.month, p.dob.day, p.dob.year); printf("Salary: %5.2f\n", p.salary);switch(p.ms.status){case married:printf("Marriage Date: %d/%d/%d\n", p.ms.u.dom.month, p.ms.u.dom.day, p.ms.u.dom.year);}}Page 64, Exercise 3#include <stdio.h>#include <string.h>typedef struct {double length, width;} rectStuff;typedef struct {double base, height;} triStuff;typedef struct {char name[10];enum tagField {rectangle, triangle, circle} shapeType;union {rectStuff rect;triStuff tri;double radius;} stats;}shape;void printShape(shape);int main(){shape s1, s2, s3;strcpy(, "rectangle");s1.shapeType = rectangle;s1.stats.rect.length = 10;s1.stats.rect.width = 20;strcpy(, "triangle");s2.shapeType = triangle;s2.stats.tri.base = 102;s2.stats.tri.height = 450;strcpy( ,"circle");s3.stats.radius = 2.5;/* printf("%f\n",s3.stats.radius);*/printShape(s1);printShape(s2);printShape(s3);}void printShape(shape s){/*print out the information on a shape */printf("Name: %s\n", );switch(s.shapeType){case rectangle:printf("\tLength:%f\n", s.stats.rect.length);printf("\tWidth:%f\n\n", s.stats.rect.width);break;case triangle:printf("\tBase:%f\n", s.stats.tri.base);printf("\tHeight:%f\n\n", s.stats.tri.height);break;case circle:printf("Radius:%f\n",s.stats.radius);break;}}Page 72, Exercise 2: readPoly() & printPoly()void printPoly(polynomial terms [], int n){/*print the polynomial*/int i;for (i = 0;i < n-1; i++)printf("%5.2fx^%d +", terms[i].coef, terms[i].expon);printf("%5.2fx^%d\n", terms[n-1].coef, terms[n-1].expon); }void readPoly(polynomial terms [], int *n){/*read in a polynomial*/int i,expon;float coef;printf ("Enter the number of terms in your polynomial: ");scanf("%d", n);while (*n >= MAX_TERMS) {printf("Too many terms in the polynomial\n");printf("Number of terms: ");scanf("%d", n);}for (i= 0; i < *n; i++) {printf("Coefficient: ");scanf("%f", &coef);printf("Exponent: ");。

2020年智慧树知道网课《数据结构(全英文)》课后章节测试满分答案

2020年智慧树知道网课《数据结构(全英文)》课后章节测试满分答案

第一章测试1【单选题】(10分) ThealgorithmandflowchartcanhelpustoA.TostorethedataB.ToknowthememorycapacityC.IdentifythedatatypeofavariableD.Specifytheproblemcompletelyandclearly2【单选题】(10分) TherhombusordiamondshapeinflowchartingdenotesA.DecisionB.InputC.InitializationD.Output3【单选题】(10分) Whichofthefollowingisnotanadvantageofaflowchart?A.EfficientcodingB.BettercommunicationC.SystematictestingD.Improperdocumentation4【单选题】(10分) Theflowchartsymbolsusedforstartandstopoperationsarecalledas_______.A.decisionB.processingC.terminalsD.connectors5【单选题】(10分)TheformulaF n=F n-1+F n-2willproduceA.FibonacciNumberB.RamanujanNumberC.PrimeNumberD.EulerNumber6【单选题】(10分) ThemainmeasuresfortheefficiencyofanalgorithmareA.ComplexityandcapacityB.ProcessorandmemoryC.TimeandspaceD.Dataandspace7【单选题】(10分) WhichoneofthefollowingistheconstanttimecomplexityintermsofBig-OhnotationA.O(1)B.O(n2)C.O(n3)D.O(n)8【单选题】(10分)Whatisthetimecomplexityofthefollowingcode?inta=0;for(i=0;i<n;i++){for(j=n;j>i;j--){a=a+i+j;}}A.O(nlog n)B.O(n)C.O(n2)D.O(1)9【单选题】(10分) Whichoneofthefollowingisanexampleforexponentialtimecomplexity?A.O(n2)B.O(2n)C.O(n)D.O(1)10【单选题】(10分)Forlargervaluesof n,whichonerepresentstheslowesttime?A.O(n2)B.O(2n)C.O(n)D.O(n!)第二章测试1【单选题】(10分) Deletionofanelementfromthearrayreducesthesizeofarrayby___________.A.threeB.twoC.zeroD.one2【单选题】(10分)Assumingthatint isof4bytes,whatisthesizeof intarr[10];?A.30B.10C.40D.3【单选题】(10分) Twodimensionalarraysareusefulwhentheelementsbeingprocessedaretobearran gedintheformof___________.A.NoneoftheaboveB.Both(a)and(b)C.rowsD.columns4【单选题】(10分)Inthepolynomial,A(x)=3x2+2x+4,thedegreeofthispolynomialisA.3B.1C.D.5【单选题】(10分)Inthepolynomial,A(x)=3x2+2x+4,coefficientoffirsttermisA.2B.1C.D.36【单选题】(10分) Amatrixhavingalargernumberofelementswithzerovaluesthanthenumberofnon-zeroelem entsissaidtobea_____________.A.triangularmatrixB.zeromatrixC.diagonalmatrixD.sparsematrix7【单选题】(10分)WhilerepresentingthesparsematrixA(m×n)withtnon-zerotermsin3-tuplesform,the sizeofthematrixbecomesA.t×nB.m×nC.3×tD.(t+1)×38【单选题】(10分)Consideringasparseof m×n matrixwith t non-zeroterms,in FAST_TRANSPOSE algorithm,thesi zeofone-dimensionalarray(SorT)isequalto:A.n+tB.mC.nt9【单选题】(10分)Consideringasparseof m×n matrixwith t non-zeroterms,thetimecomplexityof TRANS POSE algorithmis:A.O(n*t)B.O(n+t)C.O(n t)D.O(n-t)10【单选题】(10分)Whichofthefollowingstatementistrueregarding TRANSPOSE and FAST_TRANSPOSE algorit hms.A.NoneoftheaboveB.The TRANSPOSE algorithmisslowerthan FAST_TRANSPOSEC.TheTRANSPOSEalgorithmisfasterthanFAST_TRANSPOSETimecomplexitiesofTRANSPOSEandFAST_TRANSPOSEaresame第三章测试1【单选题】(10分) Theelementisinsertedfirstandwillberemovedlastin_____________.A.queueB.stackC.noneoftheaboveD.linkedlist2【单选题】(10分)Theexpression1*2^3*4^5*6isevaluatedas(^isforpower,asin a^b=a b):A.49152B.173458C.162^30D.32^303【单选题】(10分) Thedatastructurerequiredtocheckwhetheranexpressioncontainsbalancedparenthesisis?A.TreeB.ArrayC.QueueD.Stack4【单选题】(10分)Thepostfixformof A*B+C/D is?A.AB*CD/+B.ABCD+/*C.A*BC+/DD.5【单选题】(10分) Whichdatastructureisneededtoconvertinfixnotationtopostfixnotation?A.StackB.BranchC.QueueD.Tree6【单选题】(10分) Transformthefollowinginfixexpressiontoprefixform.((C*2)+1)/(A+B)A./+*C21+ABB.AB+12C*+/C.NoneoftheaboveD.7【单选题】(10分)Transformthefollowinginfixexpressiontopostfixform.(A+B)*(C-D)/EA.AB+CD-*E/B.AB*C+D/-C.AB+CD*-/ED.ABC*CD/-+8【单选题】(10分) Astackisadatastructureinwhichallinsertionsanddeletionsaremaderespectivelyat:A.atanypositionB.boththeendsC.inthemiddleD.oneend9【单选题】(10分) Whichofthefollowingapplicationsmayuseastack?:A.AlloftheaboveB.SyntaxanalyzerforacompilerC.AparenthesisbalancingprogramD.Keepingtrackoflocalvariablesatruntime10【单选题】(10分) Whichofthefollowingstatementiscorrect.A.NoneoftheaboveB. ApostfixexpressionismerelythereverseoftheprefixexpressionC.PostfixandprefixexpressionsuseparenthesisD. Apostfixexpressionisnotthereverseoftheprefixexpression第四章测试1【单选题】(10分) Aqueueisadatastructureinwhichallinsertionsanddeletionsaremaderespectivelyat:A.rearandfrontB.frontandrearC.rearandrearD.frontandfront2【单选题】(10分) Thefollowingdatastructureisusedforschedulingofjobsduringbatchprocessingincomputer s.A.stackB.queueC.linkedlistD.tree3【单选题】(10分) Inaqueuethedeletionsaretakeplaceat_________.A.NoneoftheaboveB.topC.frontD.rear4【单选题】(10分) Inaqueuetheinsertionsaretakeplaceat_________.A.rearB.topC.NoneoftheaboveD.front5【单选题】(10分)Incircularqueue,thefrontwillalwayspointtooneposition__________fromthefirstelementint hequeue.A.leftB.clockwiseC.counterclockwiseD.right6【单选题】(10分)Whichofthefollowingisnotthetypeofqueue.A.priorityqueueB.doubleendedqueueC.circularqueueD.singleendedqueue7【单选题】(10分)Oneoftheadvantageofcircularqueueis_____________.A.NoneoftheaboveB.effectiveuseofmemoryC.easiercomputationsD.deletingelementsbasedonpriority8【单选题】(10分) Whatisthetimecomplexityofalinearqueuehaving n elements?A.O(nlogn)B.O(logn)C.O(1)D.O(n)9【单选题】(10分)Whatisadequeue?A.AqueueimplementedwithadoublylinkedlistB.Aqueuewithinsert/deletedefinedforfrontendofthequeueC.Aqueuewithinsert/deletedefinedforbothfrontandrearendsofthequeueD. Aqueueimplementedwithbothsinglyanddoublylinkedlist10【单选题】(10分) Onedifferencebetweenaqueueandastackis:A.Queuesrequiredynamicmemory,butstacksdonot.B.Stacksrequiredynamicmemory,butqueuesdonot.C.Stacksusetwoendsforaddinganddeleting,butqueuesuseone.D.Queuesusetwoendsforaddinganddeleting,butstacksuseone.第五章测试1【单选题】(10分) Alinearlistofdataelementswhereeachelementcallednodeisgivenbymeansofpointeriscalle dA.nodelistB.linkedlistC.queueD.stack2【单选题】(10分)Consideranimplementationofunsortedsinglylinkedlist.Supposeithasrepresentationwhich aheadpointeronly.Giventherepresentation,whichofthefollowingoperationcanbeimpleme ntedinO(1)time?(I).Insertionatthefrontofthelinkedlist.(II).Insertionattheendofthelinkedlist.(III).Deletionofthefrontnodeofthelinkedlist.(IV).Deletionofthelastnodeofthelinkedlist.A.IandIIIB.I,II,andIIIC.I,II,andIVD.IandII3【单选题】(10分) Whatisthetimecomplexitytocountthenumberofelementsinthelinkedlist?A.O(1)B.O(n2)C.O(logn)D.O(n)4【单选题】(10分) InwhichofthefollowinglinkedliststherearenoNULLlinks?A.DoublylinkedlistB.NoneoftheaboveC.SinglylinkedlistD.Circularlinkedlist5【单选题】(10分)Indoublylinkedlists,traversalcanbeperformed?A.OnlyinforwarddirectionB.InbothdirectionsC.NoneD.Onlyinreversedirection6【单选题】(10分)Whatkindoflistisbesttoanswerquestionssuchas:“Whatistheitematposition n?”A.Singly-linkedlistsB.NoneoftheaboveC.Doubly-linkedlistsD.Listimplementedwithanarray7【单选题】(10分) Inasinglylinkedlistwhichoperationdependsonthelengthofthelist.A.DeletethelastelementofthelistB.AddanelementbeforethefirstelementofthelistC.DeletethefirstelementofthelistD.Interchangethefirsttwoelementsofthelist8【单选题】(10分)Thelinkfieldinanodecontains:A.dataofcurrentnodeB.addressofthenextnodeC.dataofnextnodeD.dataofpreviousnode9【单选题】(10分)Linkedlistdatastructureoffersconsiderablesavingin:A.SpaceutilizationB.ComputationaltimeC.SpaceutilizationandcomputationaltimeD.Noneoftheabove10【单选题】(10分) Alinearlistinwhicheachnodehaspointerstopointtothepredecessorandsuccessorsnodesis calledas:A.CircularlinkedlistB.Singly-linkedlistsC.Doubly-linkedlistsD.Linearlinkedlist第六章测试1【单选题】(10分) Torepresenthierarchicalrelationshipbetweenelements,whichdatastructureissuitable?A.treeB.arrayC.stackD.queue2【单选题】(10分) Whatisthemaximumnumberchildrenthatabinarytreenodecanhave?A.1B.C.2D.33【单选题】(10分) TheinordertraversaloftreewillyieldasortedlistingofelementsoftreeinA.NoneoftheaboveB.BinarysearchtreesC.BinarytreesD.Heaps4【单选题】(10分) Ifwestorethenodesofabinarytreeinanarraywithindexstartingfromzero,therightchil dofanodehavingindex n canbeobtainedat:A.2n+2B.n+1C.(n-1)/2D.2n+15【单选题】(10分) WhichofthefollowingtraversaloutputsthedatainsortedorderinaBST?A.InorderB.PostorderC.PreorderD.Levelorder6【单选题】(10分)Toobtainaprefixexpression,whichofthefollowingtraversalsisused?A.LevelorderB.InorderC.PostorderD.Preorder7【单选题】(10分) Themaximumnumberofnodesinatreeforwhichpostorderandpreordertraversalsmaybeequ altois_______.A.B.3C.2D.18【单选题】(10分)Supposethenumbers7,5,1,8,3,6,0,9,4,2areinsertedinthatorderintoaninitiallyempty BinarySearchTree.TheBinarySearchTreeusestheusualorderingonnaturalnumbers.What istheinordertraversalsequenceoftheresultanttree?A.024*******B.7510324689C.0123456789D.98642301579【单选题】(10分)Afullbinarytreeisatreewhere________________.A.eachnodehasexactlyzeroortwochildren.B.eachnodehasexactlytwochildrenC.alltheleavesareatthesamelevel.D.eachnodehasexactlyoneortwochildren.10【单选题】(10分) Acompletebinarytreeisatreewhere________________.A. everylevelofthetreeiscompletelyfilledexceptthelastlevelB.eachnodehasexactlytwochildrenC. eachnodehasexactlyzeroortwochildrenD. eachnodehasexactlyoneortwochildren。

《数据结构》试卷( C 卷)

《数据结构》试卷( C 卷)

《数据结构》试卷C一、单项选择题(本大题共12小题,每小题2分,共24分)1.数据结构是( D )。

A.一种数据类型B.数据的存储结构C.一组性质相同的数据元素的集合D.相互之间存在一种或多种特定关系的数据元素的集合2.算法分析的目的是( B )。

A.辨别数据结构的合理性B.评价算法的效率C.研究算法中输入与输出的关系D.鉴别算法的可读性3.在线性表的下列运算中,不.改变数据元素之间结构关系的运算是( D )。

A.插入B.删除C.排序D.定位4.若进栈序列为1,2,3,4,5,6,且进栈和出栈可以穿插进行,则可能出现的出栈序列为( B )。

A.3,2,6,1,4,5 B.3,4,2,1,6,5C.1,2,5,3,4,6 D.5,6,4,2,3,15.设串sl=″Data Structures with Java″,s2=″it″,则子串定位函数index(s1,s2)的值为( D )。

A.15 B.16C.17 D.186.二维数组A[8][9]按行优先顺序存储,若数组元素A[2][3]的存储地址为1087,A[4][7]的存储地址为1153,则数组元素A[6][7]的存储地址为( A )。

A.1207 B.1209C.1211 D.12137.在按层次遍历二叉树的算法中,需要借助的辅助数据结构是( A )。

A.队列B.栈C.线性表D.有序表8.在任意一棵二叉树的前序序列和后序序列中,各叶子之间的相对次序关系( B )。

A.不一定相同B.都相同C.都不相同D.互为逆序9.若采用孩子兄弟链表作为树的存储结构,则树的后序遍历应采用二叉树的( C )。

A.层次遍历算法B.前序遍历算法C.中序遍历算法D.后序遍历算法10.若用邻接矩阵表示一个有向图,则其中每一列包含的″1″的个数为( A )。

A.图中每个顶点的入度B.图中每个顶点的出度C.图中弧的条数D.图中连通分量的数目11.图的邻接矩阵表示法适用于表示( C )。

数据结构2014(全英文) 四川大学期末考试试题

数据结构2014(全英文) 四川大学期末考试试题

四川大学期末考试试题(闭卷)A (2013 ——2014 学年第 2 学期)
课程号:课序号:1 课程名称:数据结构(in English ) 任课教师:成绩:
适用专业年级:13电子商务学生人数:159印题份数:160学号:姓名:
2 题间不留空,一般应题卷分开教务处试题编号:
教务处试题编号:
四川大学期末考试试题(闭卷)B (2013 ——2014 学年第 2 学期)
课程号:402079030课序号:0,1 ,2 课程名称:数据结构任课教师:黄勇成绩:
适用专业年级:13电子商务学生人数:159印题份数:160学号:姓名:
注:1试题字迹务必清晰,书写工整。

本题 2 页,本页为第 1 页
2 题间不留空,一般应题卷分开教务处试题编号:
four railway carriages numbered {1,2,3,4 }, which
Programming Questions.(2*10=20)
Write a program that finds the height of a binary tree.
Write an algorithm to delete the i th element in the queue.
本题 2 页,本页为第 2 页
教务处试题编号:。

数据结构c++版题库 csdn

数据结构c++版题库 csdn

数据结构c++版题库 csdnEnglish Answer:1. Arrays.Arrays are a fundamental data structure in C++ that store elements of the same type in a contiguous block of memory. They are accessed using indices, which specify the position of the element within the array.Example:cpp.int myArray[10];myArray[0] = 42;2. Vectors.Vectors are a dynamic array that automatically resize as elements are added or removed. They provide efficient insertion and deletion operations.Example:cpp.std::vector<int> myVector;myVector.push_back(42);3. Lists.Lists are a linked list data structure that store elements in a sequence of nodes. Each node contains the data and a pointer to the next node.Example:cpp.std::list<int> myList;myList.push_back(42);4. Stacks.Stacks are a Last-In, First-Out (LIFO) data structure. Elements are added and removed from the top of the stack.Example:cpp.std::stack<int> myStack;myStack.push(42);5. Queues.Queues are a First-In, First-Out (FIFO) data structure. Elements are added to the rear of the queue and removed from the front.Example:cpp.std::queue<int> myQueue;myQueue.push(42);6. Maps.Maps are a data structure that store key-value pairs. Keys are unique identifiers, while values can be of any type.Example:cpp.std::map<std::string, int> myMap;myMap["foo"] = 42;7. Sets.Sets are a data structure that store unique elements. They do not allow duplicate values.Example:cpp.std::set<int> mySet;mySet.insert(42);8. Graphs.Graphs are a data structure that represent relationships between objects. They consist of vertices (nodes) and edges (connections between vertices).Example:cpp.std::map<int, std::vector<int>> myGraph;myGraph[1].push_back(2);9. Trees.Trees are a hierarchical data structure that represent a parent-child relationship between nodes.Example:cpp.struct Node {。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Final Examination Paper on Data Structures(A)I、Fill Vacant Position (1′×10=10′)1、____________is the name for the case when a function invokes itself or invokes asequence of other functions,one of which eventually invokes the __________again.2、In a __________ data structure, all insertions and deletions of entries are made atone end. It is particularly useful in applications involving __________.3、In c++ , we use ____________operator to implement the circular queues.4、In processing a contiguous list with n entries: insert and remove require timeapproximately to _________. And clear, empty, full, size operate in ________ time.5、One of method of searching is ____________________that requires ordered list.6、The time complexity of the quicksort is______________.7、Only __________ ____________graph has topological order.II、Multiple choice (2′×10=20′)1、In a tree, ______are vertices with the same parent. ( )A. childrenB. siblingC. adjacentD. leaf2、A queue is a version of ( )A. linked listB. LIFO listC. sequential listD. FIFO list3、How many shapes of binary trees with four nodes are there ( )A. 12B.15C. 14D. 134、Among sorting algorithms, which kind of algorithm is divide-and-conquer sorting( )A. shell sortB. heap sortC. merge sortD. inserting sort5、For the following graph, one of results of depth_first traversal is ( )A. abcdefghiB. abcdeighfC. acbdieghfD.abdeighfc6、In a binary tree, if the result of traversing under preorder is the same as that underinorder, then( )A. It is only a binary tree with one nodeB. It is either empty, or the left subtree of any node of the tree is emptyC. It is only an empty binary treeD. It is either empty, or the right subtree of an node of the tree is empty7、There are _______solutions to the problem of placing four queens on a 4×4 board.( )A. 2B. 3C. 6D. 48、Which function is smallest order of magnitude? ( )A. 2 nB. n + lgnC.n 0.1D.100009、The time requirement of retrieving a given target in hash table with n entries is( )A. O(n)B. O(log2n)C. O(1)D.O(nlog2n)10、For the following binary tree, the result of traversing under postorder is ( )A. abcdefghiB. dgbechfiaC. gdbaehifcD. gdbehifcaIII、Analyze and Calculate ( 10′)Let A be a upper triangular matrix andSuppose that(a) Elements of A are stored in row-major ordering(b) Each element occupies m memory locations(c) Indexing begins at 0Please give the calculating formula of loc(aij)(address of the element aij)IV、Comprehensive Problem(7′×6=42′)1、Draw a diagram to illustrate the configuration of linked nodes that is created bythe following statement.Node *p0=new Node (a);Node *p1=p0→next=new Node(b);Node *p2=p1→next=new Node(c,p1);2、Briefing the idea of Shellsort .3、By hand, trace the action of heap_sort on the following lists. Draw the initial tree towhich the list corresponds, show how it is converted into a heap, and show the resulting heap as each entry is removed from the top and the new entry inserted.25 31 36 28 19 12 224、Suppose that(a) A hash table contains hash_size=16 position indexed from 0 to 15(b) A hash function H(key)=(key*3)%13(c) The following keys are to be mapped into the table:10 120 33 45 58 26 3 27 200 400 2Draw the hash table with the collision resolution oflinear probing.5、Construct a minimal spanning tree ofthe following connected network..6、Given a sequence of keys:A , Z, B,Y, C, X, D, W, E, V, FInsert the keys in the order shown above, to build them into an A VL tree (draw the principal A VL tree).V、Develop Algorithm(18′)For linked implementation of binary trees, we have the following class specifications: template <class Entry>struct Binary_node {Entry data;Binary_node <Entry>*left;Binary_node <Entry>*right; };template <class Entry>class Binary_tree{protected:Binary_node<Entry>*root;int recursive_height (Binary_node<Entry> *sub_root);public:int height(); //other function; };template <class Entry>int Binary_tree<Entry>::height() {recursive_height(root);}Write the function recursive_height to computethe height ofa binary tree.Answer of Final Examination Paper On Data Structures (A)I. 1、Recursion first function 2、stack reversing3、modulus ( or % or mod)4、O(n) O(1) (or constant)5、binary search6、O(n log2n)7、directed with no cycleII. 1、B 2、D 3、A 4、C 5、D 6、B 7、A 8、D 9、C 10、DIII.(不写不扣分)IV. 1、2、Repeat(1) Choosethe increment di satsifies the followings(a) d1<n, di+1 < di(b) di is an integer(2) Partition all entries into di groups (distance between entries is di)(3) For each group,do straight insertion sortWhile (di >1)、3、4、H(10)=2 H(120)=7 H(33)=6 H(45)=3 H(58)=3H(26)=11 H(3)=7 H(27)=1 H(200)=0 H(400)=2 H(2)=40 1 2 3 4 5 6 7 8 9 10 11 12200 27 10 45 58 400 33 120 3 2 26 5、6、V.int Binary_tree<entry>::recursive_height(Binary_node<entry>*&sub_root) { int l,r,h; if(sub_root==NULL) return 0;l=recursive_height(sub_root->left);r=recursive_height(sub_root->right);h=1+(l>r?l:r);returnh;}。

相关文档
最新文档