Dada una lista enlazada no ordenada de enteros. La tarea es ordenar la Lista Vinculada en una onda como Línea. Se dice que una lista enlazada se ordena en forma de onda si la lista después de la ordenación tiene la forma:
list[0] >= list[1] <= list[2] >= …..
Donde lista[i] denota los datos en el i-ésimo Node de la lista enlazada.
Ejemplos :
Input : List = 2 -> 4 -> 6 -> 8 -> 10 -> 20 Output : 4 -> 2 -> 8 -> 6 -> 20 -> 10 Input : List = 3 -> 6 -> 5 -> 10 -> 7 -> 20 Output : 6 -> 3 -> 10 -> 5 -> 20 -> 7
Una solución simple es usar la clasificación. Primero ordene la lista de enlaces de entrada, luego intercambie todos los elementos adyacentes.
Por ejemplo, deje que la lista de entrada sea 3 -> 6 -> 5 -> 10 -> 7 -> 20 . Después de ordenar, obtenemos 3 -> 5 -> 6 -> 7 -> 10 -> 20 . Después de intercambiar elementos adyacentes, obtenemos 5 -> 3 -> 7 -> 6 -> 20 -> 10 que es la lista requerida en forma de onda.
Complejidad de tiempo : O(N*logN), donde N es el número de Nodes en la lista.
Solución eficiente : esto se puede hacer en tiempo O (n) haciendo un solo recorrido de la lista dada. La idea se basa en el hecho de que si nos aseguramos de que todos los elementos con posiciones pares (en el índice 0, 2, 4, ..) sean mayores que sus elementos impares adyacentes, no tenemos que preocuparnos por los elementos con posiciones impares. Los siguientes son pasos simples.
Nota : Suponiendo que los índices en la lista comiencen desde cero. Es decir, list[0] representa los primeros elementos de la lista enlazada.
Atraviese todos los elementos posicionados pares de la lista enlazada de entrada y haga lo siguiente.
- Si el elemento actual es más pequeño que el elemento impar anterior, intercambie anterior y actual.
- Si el elemento actual es más pequeño que el siguiente elemento impar, cambie el siguiente y el actual.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program to sort linked list // in wave form #include <climits> #include <iostream> using namespace std; // A linked list node struct Node { int data; struct Node* next; }; // Function to add a node at the // beginning of Linked List void push(struct Node** head_ref, int 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; } // Function get size of the list int listSize(struct Node* node) { int c = 0; while (node != NULL) { c++; node = node->next; } return c; } // Function to print the list void printList(struct Node* node) { while (node != NULL) { cout << node->data << " "; node = node->next; } } /* UTILITY FUNCTIONS */ /* Function to swap two integers */ void swap(int* a, int* b) { int temp; temp = *a; *a = *b; *b = temp; } // Function to sort linked list in // wave form void sortInWave(struct Node* head) { struct Node* current = head; struct Node* prev = NULL; // Variable to track even position int i = 0; // Size of list int n = listSize(head); // Traverse all even positioned nodes while (i < n) { if (i % 2 == 0) { // If current even element is // smaller than previous if (i > 0 && (prev->data > current->data)) swap(&(current->data), &(prev->data)); // If current even element is // smaller than next if (i < n - 1 && (current->data < current->next->data)) swap(&(current->data), &(current->next->data)); } i++; prev = current; current = current->next; } } // Driver program to test above function int main() { struct Node* start = NULL; /* The constructed linked list is: 10, 90, 49, 2, 1, 5, 23*/ push(&start, 23); push(&start, 5); push(&start, 1); push(&start, 2); push(&start, 49); push(&start, 90); push(&start, 10); sortInWave(start); printList(start); return 0; }
Java
// Java program to sort linked list // in wave form class GFG { // A linked list node static class Node { int data; Node next; }; // Function to add a node at the // beginning of Linked List 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; } // Function get size of the list static int listSize( Node node) { int c = 0; while (node != null) { c++; node = node.next; } return c; } // Function to print the list static void printList( Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } // Function to sort linked list in // wave form static Node sortInWave( Node head) { Node current = head; Node prev = null; // Variable to track even position int i = 0; // Size of list int n = listSize(head); // Traverse all even positioned nodes while (i < n) { if (i % 2 == 0) { // If current even element is // smaller than previous if (i > 0 && (prev.data > current.data)) { int t = prev.data; prev.data = current.data; current.data = t; } // If current even element is // smaller than next if (i < n - 1 && (current.data < current.next.data)) { int t = current.next.data; current.next.data = current.data; current.data = t; } } i++; prev = current; current = current.next; } return head; } // Driver Code public static void main(String args[]) { Node start = null; /* The constructed linked list is: 10, 90, 49, 2, 1, 5, 23*/ start = push(start, 23); start = push(start, 5); start = push(start, 1); start = push(start, 2); start = push(start, 49); start = push(start, 90); start = push(start, 10); start = sortInWave(start); printList(start); } } // This code is contributed by Arnab Kundu
Python3
# Python3 program to sort linked list # in wave form # A linked list node class Node: def __init__(self): self.data = 0 self.next = None # Function to add a node at the # beginning of Linked List def push( head_ref, new_data): ''' allocate node ''' new_node = 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 # Function get size of the list def listSize(node): c = 0; while (node != None): c += 1 node = node.next; return c; # Function to print the list def printList(node): while (node != None): print(node.data, end = ' ') node = node.next; # Function to sort linked list in # wave form def sortInWave(head): current = head; prev = None; # Variable to track even position i = 0; # Size of list n = listSize(head); # Traverse all even positioned nodes while (i < n): if (i % 2 == 0): # If current even element is # smaller than previous if (i > 0 and (prev.data > current.data)): (current.data), (prev.data) = (prev.data), (current.data) # If current even element is # smaller than next if (i < n - 1 and (current.data < current.next.data)): (current.data), (current.next.data) = (current.next.data), (current.data) i += 1 prev = current; current = current.next; # Driver program to test above function if __name__=='__main__': start = None; ''' The constructed linked list is: 10, 90, 49, 2, 1, 5, 23''' start = push(start, 23); start = push(start, 5); start = push(start, 1); start = push(start, 2); start = push(start, 49); start = push(start, 90); start = push(start, 10) sortInWave(start) printList(start); # This code is contributed by pratham76
C#
// C# program to sort linked list // in wave form using System; class GFG{ // A linked list node class Node { public int data; public Node next; }; // Function to add a node at the // beginning of Linked List 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; } // Function get size of the list static int listSize( Node node) { int c = 0; while (node != null) { c++; node = node.next; } return c; } // Function to print the list static void printList( Node node) { while (node != null) { Console.Write(node.data + " "); node = node.next; } } // Function to sort linked list in // wave form static Node sortInWave( Node head) { Node current = head; Node prev = null; // Variable to track even position int i = 0; // Size of list int n = listSize(head); // Traverse all even positioned nodes while (i < n) { if (i % 2 == 0) { // If current even element is // smaller than previous if (i > 0 && (prev.data > current.data)) { int t = prev.data; prev.data = current.data; current.data = t; } // If current even element is // smaller than next if (i < n - 1 && (current.data < current.next.data)) { int t = current.next.data; current.next.data = current.data; current.data = t; } } i++; prev = current; current = current.next; } return head; } // Driver Code public static void Main(string []args) { Node start = null; // The constructed linked list is: // 10, 90, 49, 2, 1, 5, 23 start = push(start, 23); start = push(start, 5); start = push(start, 1); start = push(start, 2); start = push(start, 49); start = push(start, 90); start = push(start, 10); start = sortInWave(start); printList(start); } } // This code is contributed by rutvik_56
Javascript
<script> // JavaScript program to sort linked list // in wave form // A linked list node class Node { constructor() { this.data = 0; this.next = null; } } // Function to add a node at the // beginning of Linked List 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; } // Function get size of the list function listSize(node) { var c = 0; while (node != null) { c++; node = node.next; } return c; } // Function to print the list function printList(node) { while (node != null) { document.write(node.data + " "); node = node.next; } } // Function to sort linked list in // wave form function sortInWave(head) { var current = head; var prev = null; // Variable to track even position var i = 0; // Size of list var n = listSize(head); // Traverse all even positioned nodes while (i < n) { if (i % 2 == 0) { // If current even element is // smaller than previous if (i > 0 && prev.data > current.data) { var t = prev.data; prev.data = current.data; current.data = t; } // If current even element is // smaller than next if (i < n - 1 && current.data < current.next.data) { var t = current.next.data; current.next.data = current.data; current.data = t; } } i++; prev = current; current = current.next; } return head; } // Driver Code var start = null; // The constructed linked list is: // 10, 90, 49, 2, 1, 5, 23 start = push(start, 23); start = push(start, 5); start = push(start, 1); start = push(start, 2); start = push(start, 49); start = push(start, 90); start = push(start, 10); start = sortInWave(start); printList(start); </script>
90 10 49 1 5 2 23