a) Void addNodeTail (Node* head, int data) { if ( head == NULL) { Head = createNode (data); Return; } Node* current = head; While (current != NULL) { Current = current->next; } Current->next = creatNode(data); } b) Void printList (Node* head) { if (head == NULL) { cout << “Danh sách rỗng” << endl; return; } Node* current = head; While (current != NULL) { Cout << current->data << “ “; Current = current->next; } Cout << endl; }
c) Void printPrimes(Node* head) {
Vector<int> primes;
Node* current = head;
While (current != NULL) { If (isPrime(current->data)) { Primes.push_back(current->data); } Current = current->next; } For (int prime : primes){ Cout << prime << “ “; } Cout << endl; }
d) Float getAverage(Node* head){
Float sum = 0; Int count = 0; Node* current = head; While (current != NULL){ Sum += current->data; Count++; Current = current->next; } Return sum / count; }
e) Int countOccurences(Node* head, int x){
Int count = 0; Node* current = head; While (current != NULL){ If (current->data = x){ Count++; } Current = current->next; } Return count; }
f) Int findLastPerfectSquare (Node* head){
Int lastPerfectSquare = -1; Node* current = head; While (current != NULL){ If (isPerfectSquare(current->data)){ lastPerfectSquare = current->data; } Current = current->next; } Return lastPerfectSquare; }
g) Int findKthElement(Node* head, int k){
Int index = 0; Node* current = head; While (current != NULL){ If (index == k){ Return current->data; } Index++; Current = current->next; } Return -1; }
h) Node* find_min(Node* head){
Node* min_node = head; Node* current = head; While (current != NULL){ If (current->data < min_node->data){ min_node = current; } Current = current->next; } Return min_node; }
Node* current = head; While (current != NULL){ If (current->data == data) { Break; } Current = current->next; } If (current == NULL){ Node* new_node = new Node{data}; new_node->next = NULL; if (head != NULL){ head->next = new_node; }else{ Head = new_node; } } } k) Void remove_k_elements_at_head(Node* head, int k){ For (int I = 0; I < k; I ++){ If ( head != NULL){ Node* next = head->next; Delete head; Head = next; } } }
l) Void remove_element_with_value(Node* head, int x){
Node* current = head; While (current != NULL){ If (current->data == x){ Node* next = current->next; Delete current; Current = next; Continue; } Current = current->next; } }