Data Structure practice-sequence table application and data structure practice Sequence
[Project-sequence table application]
Define a linear table with sequential structure storage. design the algorithm to complete the following work:
1. Delete all elements between [x, y]. The time complexity of the algorithm is O (n) and the space complexity is O (1 );
2. Moving the odd number to the front of all even numbers requires that the time complexity of the algorithm be O (n) and the space complexity be O (1 ).
Tip:
(1) Make full use of the algorithm library established above to solve the problem of creating a sequence table and outputting a linear table;
(2) To ensure the complexity, design an algorithm and use a special function to implement the algorithm;
(3) write a program for each job and publish a blog post to show your practical results.
[Reference] (Note: For details about list. h and list. cpp required in the project, click here ...)
1. Delete all elements between [x, y]. The time complexity of the algorithm is O (n) and the space complexity is O (1 );
# Include "list. h "# include <stdio. h> // Delete the void delx2y (SqList * & L, ElemType x, ElemType y) element between x and y in a linear table {int k = 0, I; // k records the number of non-x elements ElemType t; if (x> y) {t = x; x = y; y = t;} for (I = 0; I <L-> length; I ++) if (L-> data [I] <x | L-> data [I]> y) // copy elements not between [x, y] {L-> data [k] = L-> data [I]; k ++ ;} l-> length = k;} // use main to write the test code int main () {SqList * sq; ElemType a [10] =, 7,3}; CreateList (sq, a, 10); printf ("before deletion"); DispList (sq); delx2y (sq, 4, 7 ); printf ("deleted"); DispList (sq); return 0 ;}
2. Moving the odd number to the front of all even numbers requires that the time complexity of the algorithm be O (n) and the space complexity be O (1 ).
# Include "list. h "# include <stdio. h> // after the movement ends, the odd number is left and the even number is right void move (SqList * & L) {int I = 0, j = L-> length-1; ElemType tmp; while (I <j) {while (I <j) & (L-> data [j] % 2 = 0) // from right to left, find the first odd number (even number, ignore it) j --; while (I <j) & (L-> data [I] % 2 = 1 )) // from left to right, find the first even number (ignore if it is an odd number) I ++; if (I <j) // if it does not reach the "Demarcation Line ", exchange the odd number on the right and the even number on the left {tmp = L-> data [I]; L-> data [I] = L-> data [j]; l-> data [j] = tmp ;}// wait until the loop goes up, continue searching, and switch if necessary} // use main to write the test code int main () {SqList * sq; ElemType a [10] = {5, 8, 7, 0, 2, 4, 9, 6, 7, 3}; CreateList (sq, a, 10); printf ("before operation "); dispList (sq); move (sq); printf ("post-operation"); DispList (sq); return 0 ;}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.