Exam:
A linear table L with a length of N is compiled with an algorithm with a time complexity of O (N) and a space complexity of O (1). This algorithm deletes all data elements with a value of X in a linear table.
Solution:
Use K to record the number of elements not equal to X in the sequence table (that is, the number of elements to be saved), and scan the L side to count K, put K positions in front of the element image not equal to X, and modify the length of L.
Void del_x (sqlist & L, elementype X) {int K = 0; For (INT I = 0; I <L. length; I ++) if (L. data [I]! = X) {L. data [k] = L. data [I]; k ++; // The number of elements not equal to x plus 1} l. length = K; // The length of the sequence table L is equal to k}
Complete code implementation:
# Include <stdio. h> # include <stdlib. h> # define maxsize 50 typedef struct {int data [maxsize]; int length;} sqlist; void del_x (sqlist & L, int X) {int K = 0; for (INT I = 0; I <L. length; I ++) if (L. data [I]! = X) {L. data [k] = L. data [I]; k ++; // The number of elements not equal to x plus 1} l. length = K; // The length of the sequence table L is k} int main () {sqlist data; data. length = 10; for (INT I = 1; I <data. length; I = I + 2) data. data [I] = I; for (INT I = 0; I <data. length; I = I + 2) data. data [I] = 0; // data before calling the function. data [10] = {,} // call the function to delete element 0 and modify the length. del_x (data, 0); // displays the sequence table after deletion. for (INT I = 0; I <data. length; I ++) printf ("% d", Data. data [I]); System ("pause ");}
From: I love programmers
Invalid.