Dada una lista enlazada de enteros. La tarea es escribir un programa para modificar la lista enlazada de modo que todos los números pares aparezcan antes que todos los números impares en la lista enlazada modificada. No es necesario mantener el orden de los Nodes pares e impares igual que en la lista original, la tarea es simplemente reorganizar los Nodes de modo que todos los Nodes con valores pares aparezcan antes que los Nodes con valores impares.
Ver también : Segregación de Nodes pares e impares en una lista enlazada
Ejemplos :
Entrada : 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> NULL
Salida : 10 -> 8 -> 6 -> 4 -> 2 -> 1 -> 3 -> 5 -> 7 -> 9 -> NULO
Entrada : 4 -> 3 -> 2 -> 1 -> NULO
Salida : 2 -> 4 -> 3 -> 1 -> NULO
La idea es empujar iterativamente todos los elementos de la lista enlazada a deque según las siguientes condiciones:
- Comience a recorrer la lista enlazada y, si un elemento es par, empújelo al frente del Deque y,
- Si el elemento es impar, empújelo hacia la parte posterior del Deque.
Finalmente, reemplace todos los elementos de la lista enlazada con los elementos de Deque comenzando desde el primer elemento.
A continuación se muestra la implementación del enfoque anterior:
C++
// CPP program to segregate even and // odd nodes in a linked list using deque #include <bits/stdc++.h> using namespace std; /* Link list node */ struct Node { int data; struct Node* next; }; /*UTILITY FUNCTIONS*/ /* Push a node to linked list. Note that this function changes the head */ void push(struct Node** head_ref, char new_data) { /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } // printing the linked list void printList(struct Node* head) { struct Node* temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } } // Function to rearrange even and odd // elements in a linked list using deque void evenOdd(struct Node* head) { struct Node* temp = head; // Declaring a Deque deque<int> d; // Push all the elements of // linked list in to deque while (temp != NULL) { // if element is even push it // to front of the deque if (temp->data % 2 == 0) d.push_front(temp->data); else // else push at the back of the deque d.push_back(temp->data); temp = temp->next; // increase temp } temp = head; // Replace all elements of the linked list // with the elements of Deque starting from // the first element while (!d.empty()) { temp->data = d.front(); d.pop_front(); temp = temp->next; } } // Driver code int main() { struct Node* head = NULL; push(&head, 10); push(&head, 9); push(&head, 8); push(&head, 7); push(&head, 6); push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); cout << "Given linked list: "; printList(head); evenOdd(head); cout << "\nAfter rearrangement: "; printList(head); return 0; }
Java
// JAVA program to segregate // even and odd nodes in a // linked list using deque import java.util.*; class GFG{ // Link list node static class Node { int data; Node next; }; // UTILITY FUNCTIONS // Push a node to linked list. // Note that this function // changes the head static Node push(Node head_ref, int new_data) { // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // link the old list off // the new node new_node.next = head_ref; // move the head to point // to the new node head_ref = new_node; return head_ref; } // Printing the linked list static void printList(Node head) { Node temp = head; while (temp != null) { System.out.printf("%d ", temp.data); temp = temp.next; } } // Function to rearrange even // and odd elements in a linked // list using deque static void evenOdd(Node head) { Node temp = head; // Declaring a Deque Deque<Integer> d = new LinkedList<>(); // Push all the elements of // linked list in to deque while (temp != null) { // if element is even push it // to front of the deque if (temp.data % 2 == 0) d.addFirst(temp.data); else // else push at the // back of the deque d.add(temp.data); // increase temp temp = temp.next; } temp = head; // Replace all elements of // the linked list with the // elements of Deque starting // from the first element while (!d.isEmpty()) { temp.data = d.peek(); d.pollFirst(); temp = temp.next; } } // Driver code public static void main(String[] args) { Node head = null; head = push(head, 10); head = push(head, 9); head = push(head, 8); head = push(head, 7); head = push(head, 6); head = push(head, 5); head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); System.out.print("Given linked list: "); printList(head); evenOdd(head); System.out.print("\nAfter rearrangement: "); printList(head); } } // This code is contributed by shikhasingrajput
Python
# Python program to segregate even and # odd nodes in a linked list using deque import collections # Node class class Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # UTILITY FUNCTIONS # Push a node to linked list. Note that this function # changes the head def push( head_ref, new_data): # allocate node new_node = Node(0) # put in the data new_node.data = new_data # link the old list off the new node new_node.next = (head_ref) # move the head to point to the new node (head_ref) = new_node return head_ref # printing the linked list def printList( head): temp = head while (temp != None): print( temp.data, end = " ") temp = temp.next # Function to rearrange even and odd # elements in a linked list using deque def evenOdd( head): temp = head # Declaring a Deque d = collections.deque([]) # Push all the elements of # linked list in to deque while (temp != None) : # if element is even push it # to front of the deque if (temp.data % 2 == 0): d.appendleft(temp.data) else: # else push at the back of the deque d.append(temp.data) temp = temp.next # increase temp temp = head # Replace all elements of the linked list # with the elements of Deque starting from # the first element while (len(d) > 0) : temp.data = d[0] d.popleft() temp = temp.next # Driver code head = None head = push(head, 10) head = push(head, 9) head = push(head, 8) head = push(head, 7) head = push(head, 6) head = push(head, 5) head = push(head, 4) head = push(head, 3) head = push(head, 2) head = push(head, 1) print( "Given linked list: ", end = "") printList(head) evenOdd(head) print("\nAfter rearrangement: ", end = "") printList(head) # This code is contributed by Arnab Kundu
C#
// C# program to segregate // even and odd nodes in a // linked list using deque using System; using System.Collections.Generic; class GFG{ // Link list node public class Node { public int data; public Node next; }; // UTILITY FUNCTIONS // Push a node to linked list. // Note that this function // changes the head static Node push(Node head_ref, int new_data) { // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // link the old list off // the new node new_node.next = head_ref; // move the head to point // to the new node head_ref = new_node; return head_ref; } // Printing the linked list static void printList(Node head) { Node temp = head; while (temp != null) { Console.Write(" " + temp.data); temp = temp.next; } } // Function to rearrange even // and odd elements in a linked // list using deque static void evenOdd(Node head) { Node temp = head; // Declaring a Deque List<int> d = new List<int>(); // Push all the elements of // linked list in to deque while (temp != null) { // if element is even push it // to front of the deque if (temp.data % 2 == 0) d.Insert(0, temp.data); else // else push at the // back of the deque d.Add(temp.data); // increase temp temp = temp.next; } temp = head; // Replace all elements of // the linked list with the // elements of Deque starting // from the first element while (d.Count != 0) { temp.data = d[0]; d.RemoveAt(0); temp = temp.next; } } // Driver code public static void Main(String[] args) { Node head = null; head = push(head, 10); head = push(head, 9); head = push(head, 8); head = push(head, 7); head = push(head, 6); head = push(head, 5); head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); Console.Write("Given linked list: "); printList(head); evenOdd(head); Console.Write("\nAfter rearrangement: "); printList(head); } } // This code is contributed by 29AjayKumar
Javascript
<script> // JavaScript program to segregate // even and odd nodes in a // linked list using deque // Link list node class Node { constructor() { this.data = 0; this.next = null; } } // UTILITY FUNCTIONS // Push a node to linked list. // Note that this function // changes the head function push(head_ref, new_data) { // allocate node var new_node = new Node(); // put in the data new_node.data = new_data; // link the old list off // the new node new_node.next = head_ref; // move the head to point // to the new node head_ref = new_node; return head_ref; } // Printing the linked list function printList(head) { var temp = head; while (temp != null) { document.write(" " + temp.data); temp = temp.next; } } // Function to rearrange even // and odd elements in a linked // list using deque function evenOdd(head) { var temp = head; // Declaring a Deque var d = []; // Push all the elements of // linked list in to deque while (temp != null) { // if element is even push it // to front of the deque if (temp.data % 2 == 0) d.unshift(temp.data); // else push at the // back of the deque else d.push(temp.data); // increase temp temp = temp.next; } temp = head; // Replace all elements of // the linked list with the // elements of Deque starting // from the first element while (d.length != 0) { temp.data = d[0]; d.shift(); temp = temp.next; } } // Driver code var head = null; head = push(head, 10); head = push(head, 9); head = push(head, 8); head = push(head, 7); head = push(head, 6); head = push(head, 5); head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); document.write("Given linked list: "); printList(head); evenOdd(head); document.write("<br>After rearrangement: "); printList(head); // This code is contributed by rdtank. </script>
Given linked list: 1 2 3 4 5 6 7 8 9 10 After rearrangement: 10 8 6 4 2 1 3 5 7 9
Complejidad temporal : O(N)
Espacio auxiliar : O(N), donde N es el número total de Nodes en la lista enlazada.
Publicación traducida automáticamente
Artículo escrito por Shahnawaz_Ali y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA