Dada una lista enlazada individualmente, reorganice la lista para que los Nodes pares e impares se alternen en la lista.
Hay dos formas posibles de este reordenamiento. Si el primer dato es impar, entonces el segundo Node debe ser par. El tercer Node debe ser impar y así sucesivamente. Observe que es posible otro arreglo donde el primer Node es par, el segundo impar, el tercero par y así sucesivamente.
Ejemplos:
Input: 11 -> 20 -> 40 -> 55 -> 77 -> 80 -> NULL Output: 11 -> 20 -> 55 -> 40 -> 77 -> 80 -> NULL 20, 40, 80 occur in even positions and 11, 55, 77 occur in odd positions. Input: 10 -> 1 -> 2 -> 3 -> 5 -> 6 -> 7 -> 8 -> NULL Output: 1 -> 10 -> 3 -> 2 -> 5 -> 6 -> 7 -> 8 -> NULL 1, 3, 5, 7 occur in odd positions and 10, 2, 6, 8 occur at even positions in the list
Método 1 (simple):
en este método, creamos dos pilas: pares e impares. Recorremos la lista y cuando encontramos un Node par en una posición impar empujamos la dirección de este Node a la pila par. Si encontramos un Node impar en una posición par, insertamos la dirección de este Node en Odd Stack.
Después de recorrer la lista, simplemente extraemos los Nodes en la parte superior de las dos pilas e intercambiamos sus datos. Seguimos repitiendo este paso hasta que las pilas se vacían.
Step 1: Create two stacks Odd and Even. These stacks will store the pointers to the nodes in the list Step 2: Traverse list from start to end, using the variable current. Repeat following steps 3-4. Step 3: If the current node is even and it occurs at an odd position, push this node's address to stack Even. Step 4: If the current node is odd and it occurs at an even position, push this node's address to stack Odd.
[END OF TRAVERSAL]. Step 5: The size of both the stacks will be the same. While both the stacks are not empty exchange the nodes at the top of the two stacks and pop both nodes from their respective stacks. Step 6: The List is now rearranged. STOP
C++
// CPP program to rearrange nodes // as alternate odd even nodes in // a Singly Linked List #include <bits/stdc++.h> using namespace std; // Structure node struct Node { int data; struct Node* next; }; // A utility function to print // linked list void printList(struct Node* node) { while (node != NULL) { cout << node->data << " "; node = node->next; } cout << endl; } // Function to create newNode // in a linkedlist Node* newNode(int key) { Node* temp = new Node; temp->data = key; temp->next = NULL; return temp; } // Function to insert at beginning Node* insertBeg(Node* head, int val) { Node* temp = newNode(val); temp->next = head; head = temp; return head; } // Function to rearrange the // odd and even nodes void rearrangeOddEven(Node* head) { stack<Node*> odd; stack<Node*> even; int i = 1; while (head != nullptr) { if (head->data % 2 != 0 && i % 2 == 0) { // Odd Value in Even Position // Add pointer to current node // in odd stack odd.push(head); } else if (head->data % 2 == 0 && i % 2 != 0) { // Even Value in Odd Position // Add pointer to current node // in even stack even.push(head); } head = head->next; i++; } while (!odd.empty() && !even.empty()) { // Swap Data at the top of // two stacks swap(odd.top()->data, even.top()->data); odd.pop(); even.pop(); } } // Driver code int main() { Node* head = newNode(8); head = insertBeg(head, 7); head = insertBeg(head, 6); head = insertBeg(head, 5); head = insertBeg(head, 3); head = insertBeg(head, 2); head = insertBeg(head, 1); cout << "Linked List:" << endl; printList(head); rearrangeOddEven(head); cout << "Linked List after " << "Rearranging:" << endl; printList(head); return 0; }
Producción:
Linked List: 1 2 3 5 6 7 8 Linked List after Rearranging: 1 2 3 6 5 8 7
Tiempo Complejidad : O(n)
Espacio Auxiliar : O(n)
Método 2 (eficiente):
- Separe los valores pares e impares en la lista. Después de esto, todos los valores impares aparecerán juntos seguidos de todos los valores pares.
- Divide la lista en dos listas pares e impares.
- Combinar la lista par en la lista impar
REARRANGE (HEAD) Step 1: Traverse the list using NODE TEMP. If TEMP is odd Add TEMP to the beginning of the List [END OF IF] [END OF TRAVERSAL] Step 2: Set TEMP to 2nd element of LIST. Step 3: Set PREV_TEMP to 1st element of List Step 4: Traverse using node TEMP as long as an even node is not encountered. PREV_TEMP = TEMP, TEMP = TEMP->NEXT [END OF TRAVERSAL] Step 5: Set EVEN to TEMP. Set PREV_TEMP->NEXT to NULL Step 6: I = HEAD, J = EVEN Step 7: Repeat while I != NULL and J != NULL Store next nodes of I and J in K and L K = I->NEXT, L = J->NEXT I->NEXT = J, J->NEXT = K, PTR = J I = K and J = L [END OF LOOP] Step 8: if I == NULL PTR->NEXT = J [END of IF] Step 8: Return HEAD. Step 9: End
C++
// Cpp program to rearrange nodes // as alternate odd even nodes in // a Singly Linked List #include <bits/stdc++.h> using namespace std; // Structure node struct Node { int data; struct Node* next; }; // A utility function to print // linked list void printList(struct Node* node) { while (node != NULL) { cout << node->data << " "; node = node->next; } cout << endl; } // Function to create newNode // in a linkedlist Node* newNode(int key) { Node* temp = new Node; temp->data = key; temp->next = NULL; return temp; } // Function to insert at beginning Node* insertBeg(Node* head, int val) { Node* temp = newNode(val); temp->next = head; head = temp; return head; } // Function to rearrange the // odd and even nodes void rearrange(Node** head) { // Step 1: Segregate even and odd nodes // Step 2: Split odd and even lists // Step 3: Merge even list into odd list Node* even; Node *temp, *prev_temp; Node *i, *j, *k, *l, *ptr; // Step 1: Segregate Odd and // Even Nodes temp = (*head)->next; prev_temp = *head; while (temp != nullptr) { // Backup next pointer of temp Node* x = temp->next; // If temp is odd move the node // to beginning of list if (temp->data % 2 != 0) { prev_temp->next = x; temp->next = (*head); (*head) = temp; } else { prev_temp = temp; } // Advance Temp Pointer temp = x; } // Step 2 // Split the List into Odd and // even temp = (*head)->next; prev_temp = (*head); while (temp != nullptr && temp->data % 2 != 0) { prev_temp = temp; temp = temp->next; } even = temp; // End the odd List (Make // last node null) prev_temp->next = nullptr; // Step 3: // Merge Even List into odd i = *head; j = even; while (j != nullptr && i != nullptr) { // While both lists are not // exhausted Backup next // pointers of i and j k = i->next; l = j->next; i->next = j; j->next = k; // ptr points to the latest // node added ptr = j; // Advance i and j pointers i = k; j = l; } if (i == nullptr) { // Odd list exhausts before even, // append remainder of even list // to odd. ptr->next = j; } // The case where even list exhausts // before odd list is automatically // handled since we merge the even // list into the odd list } // Driver Code int main() { Node* head = newNode(8); head = insertBeg(head, 7); head = insertBeg(head, 6); head = insertBeg(head, 3); head = insertBeg(head, 5); head = insertBeg(head, 1); head = insertBeg(head, 2); head = insertBeg(head, 10); cout << "Linked List:" << endl; printList(head); cout << "Rearranged List" << endl; rearrange(&head); printList(head); }
Producción:
Linked List: 10 2 1 5 3 6 7 8 Rearranged List 7 10 3 2 5 6 1 8
Tiempo Complejidad : O(n)
Espacio Auxiliar : O(1)
¡ Consulte el artículo completo sobre Nodes pares e impares alternativos en una lista enlazada individual para obtener más detalles!
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA