Dada una lista enlazada, reorganícela de modo que la lista convertida tenga la forma a < b > c < d > e < f .. donde a, b, c… son Nodes de datos consecutivos de la lista enlazada. Tenga en cuenta que no está permitido intercambiar datos.
Ejemplos:
Input: 1->2->3->4 Output: 1->3->2->4 Input: 11->15->20->5->10 Output: 11->20->5->15->10
Enfoque:
una solución que convierte la lista dada en forma de zigzag se analiza en una publicación anterior . La solución discutida realiza la conversión intercambiando datos de Nodes. El intercambio de datos de Nodes puede ser costoso en muchas situaciones cuando los datos contienen muchos campos. En esta publicación, se analiza una solución que realiza la conversión mediante el intercambio de enlaces.
La idea es recorrer la lista enlazada dada y verificar si el Node actual mantiene el orden en zigzag o no. Para verificar si un Node dado mantiene el orden en zigzag o no, se usa una variable ind . Si ind = 0 , entonces los datos del Node actual deben ser menores que los datos del Node adyacente y si ind = 1, los datos del Node actual deben ser mayores que los datos del Node adyacente. Si el Node actual viola el orden en zigzag, cambie la posición de ambos Nodes. Para hacer este paso, mantenga dos punteros anterior y siguiente . prev almacena el Node anterior del Node actual y next almacena el nuevo Node siguiente del Node actual. Para intercambiar ambos Nodes, se realizan los siguientes pasos:
- Hacer el siguiente Node del Node actual, el siguiente Node del Node anterior.
- Hacer que el Node actual sea el siguiente Node de su Node adyacente.
- Hacer que el Node actual sea el siguiente = siguiente Node.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program to arrange linked list in // zigzag fashion #include <bits/stdc++.h> using namespace std; /* Link list Node */ struct Node { int data; struct Node* next; }; // This function converts the Linked list in // zigzag fashion Node* zigZagList(Node* head) { if (head == NULL || head->next == NULL) { return head; } // to store new head Node* res = NULL; // to traverse linked list Node* curr = head; // to store previous node of current node Node* prev = NULL; // to store new next node of current node Node* next; // to check if current element should // be less than or greater than. // ind = 0 --> less than // ind = 1 --> greater than int ind = 0; while (curr->next) { // If elements are not in zigzag fashion // swap them. if ((ind == 0 && curr->data > curr->next->data) || (ind == 1 && curr->data < curr->next->data)) { if (res == NULL) res = curr->next; // Store new next element of current // node next = curr->next->next; // Previous node of current node will // now point to next node of current node if (prev) prev->next = curr->next; // Change next pointers of both // adjacent nodes curr->next->next = curr; curr->next = next; // Change previous pointer. if (prev) prev = prev->next; else prev = res; } // If already in zig zag form, then move // to next element. else { if (res == NULL) { res = curr; } prev = curr; curr = curr->next; } // Update info whether next element should // be less than or greater than. ind = 1 - ind; } return res; } /* UTILITY FUNCTIONS */ /* Function to push a Node */ void push(Node** head_ref, int new_data) { /* allocate Node */ struct 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; } /* Function to print linked list */ void printList(struct Node* Node) { while (Node != NULL) { printf("%d->", Node->data); Node = Node->next; } } /* Driver program to test above function*/ int main(void) { /* Start with the empty list */ struct Node* head = NULL; // create a list 4 -> 3 -> 7 -> 8 -> 6 -> 2 -> 1 // answer should be -> 3 7 4 8 2 6 1 push(&head, 1); push(&head, 2); push(&head, 6); push(&head, 8); push(&head, 7); push(&head, 3); push(&head, 4); printf("Given linked list \n"); printList(head); head = zigZagList(head); printf("\nZig Zag Linked list \n"); printList(head); return 0; }
Java
// Java program to arrange linked list in // zigzag fashion class GFG { /* Link list Node */ static class Node { int data; Node next; }; static Node head; // This function converts the Linked list in // zigzag fashion static Node zigZagList(Node head) { if (head == null || head.next == null) { return head; } // to store new head Node res = null; // to traverse linked list Node curr = head; // to store previous node of current node Node prev = null; // to store new next node of current node Node next; // to check if current element should // be less than or greater than. // ind = 0 -. less than // ind = 1 -. greater than int ind = 0; while (curr.next != null) { // If elements are not in zigzag fashion // swap them. if ((ind == 0 && curr.data > curr.next.data) || (ind == 1 && curr.data < curr.next.data)) { if (res == null) res = curr.next; // Store new next element of current // node next = curr.next.next; // Previous node of current node will // now point to next node of current node if (prev != null) prev.next = curr.next; // Change next pointers of both // adjacent nodes curr.next.next = curr; curr.next = next; // Change previous pointer. if (prev != null) prev = prev.next; else prev = res; } // If already in zig zag form, then move // to next element. else { if (res == null) { res = curr; } prev = curr; curr = curr.next; } // Update info whether next element should // be less than or greater than. ind = 1 - ind; } return res; } /* UTILITY FUNCTIONS */ /* Function to push a Node */ static void 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; head = head_ref; } /* Function to print linked list */ static void printList(Node Node) { while (Node != null) { System.out.printf("%d->", Node.data); Node = Node.next; } } // Driver Code public static void main(String[] args) { /* Start with the empty list */ head = null; // create a list 4 -> 3 -> 7 -> 8 -> 6 -> 2 -> 1 // answer should be -> 3 7 4 8 2 6 1 push(head, 1); push(head, 2); push(head, 6); push(head, 8); push(head, 7); push(head, 3); push(head, 4); System.out.printf("Given linked list \n"); printList(head); head = zigZagList(head); System.out.printf("\nZig Zag Linked list \n"); printList(head); } } // This code is contributed by Rajput-Ji
Python3
# Python3 program to arrange # linked list in zigzag fashion class Node: def __init__(self, data): self.data = data self.next = None # This function converts the # Linked list in zigzag fashion def zigZagList(head): if head == None or head.next == None: return head # To store new head res = None # To traverse linked list curr = head # To store previous node of current node prev = None # to check if current element should # be less than or greater than. # ind = 0 -. less than # ind = 1 -. greater than ind = 0 while curr.next: # If elements are not in # zigzag fashion swap them. if ((ind == 0 and curr.data > curr.next.data) or (ind == 1 and curr.data < curr.next.data)): if res == None: res = curr.next # Store new next element of current # node next = curr.next.next # Previous node of current node will # now point to next node of current node if prev: prev.next = curr.next # Change next pointers of # both adjacent nodes curr.next.next = curr curr.next = next # Change previous pointer. if prev: prev = prev.next else: prev = res # If already in zig zag form, # then move to next element. else: if res == None: res = curr prev = curr curr = curr.next # Update info whether next element # should be less than or greater than. ind = 1 - ind return res # UTILITY FUNCTIONS # Function to push a Node def push(head_ref, new_data): # put in the data new_Node = Node(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 to print linked list def printList(Node): while Node != None: print(Node.data, end = "->") Node = Node.next # Driver program to test above function if __name__ == "__main__": # Start with the empty list head = None # create a list 4 . 3 . 7 . 8 . 6 . 2 . 1 # answer should be . 3 7 4 8 2 6 1 head = push(head, 1) head = push(head, 2) head = push(head, 6) head = push(head, 8) head = push(head, 7) head = push(head, 3) head = push(head, 4) print("Given linked list") printList(head) head = zigZagList(head) print("\nZig Zag Linked list") printList(head) # This code is contributed by Rituraj Jain
C#
// C# program to arrange linked list in // zigzag fashion using System; class GFG { /* Link list Node */ public class Node { public int data; public Node next; }; static Node head; // This function converts the Linked list in // zigzag fashion static Node zigZagList(Node head) { if (head == null || head.next == null) { return head; } // to store new head Node res = null; // to traverse linked list Node curr = head; // to store previous node of current node Node prev = null; // to store new next node of current node Node next; // to check if current element should // be less than or greater than. // ind = 0 -. less than // ind = 1 -. greater than int ind = 0; while (curr.next != null) { // If elements are not in zigzag fashion // swap them. if ((ind == 0 && curr.data > curr.next.data) || (ind == 1 && curr.data < curr.next.data)) { if (res == null) res = curr.next; // Store new next element of current // node next = curr.next.next; // Previous node of current node will // now point to next node of current node if (prev != null) prev.next = curr.next; // Change next pointers of both // adjacent nodes curr.next.next = curr; curr.next = next; // Change previous pointer. if (prev != null) prev = prev.next; else prev = res; } // If already in zig zag form, then move // to next element. else { if (res == null) { res = curr; } prev = curr; curr = curr.next; } // Update info whether next element should // be less than or greater than. ind = 1 - ind; } return res; } /* UTILITY FUNCTIONS */ /* Function to push a Node */ static void 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; head = head_ref; } /* Function to print linked list */ static void printList(Node Node) { while (Node != null) { Console.Write("{0}->", Node.data); Node = Node.next; } } // Driver Code public static void Main(String[] args) { /* Start with the empty list */ head = null; // create a list 4 -> 3 -> 7 -> 8 -> 6 -> 2 -> 1 // answer should be -> 3 7 4 8 2 6 1 push(head, 1); push(head, 2); push(head, 6); push(head, 8); push(head, 7); push(head, 3); push(head, 4); Console.Write("Given linked list \n"); printList(head); head = zigZagList(head); Console.Write("\nZig Zag Linked list \n"); printList(head); } } // This code is contributed by 29AjayKumar
Javascript
<script> // JavaScript program to arrange linked list in // zigzag fashion /* Link list Node */ class Node { constructor() { this.data = 0; this.next = null; } } var head = null; // This function converts the Linked list in // zigzag fashion function zigZagList(head) { if (head == null || head.next == null) { return head; } // To store new head var res = null; // To traverse linked list var curr = head; // To store previous node of current node var prev = null; // To store new next node of current node var next; // To check if current element should // be less than or greater than. // ind = 0 -. less than // ind = 1 -. greater than var ind = 0; while (curr.next != null) { // If elements are not in zigzag fashion // swap them. if ((ind == 0 && curr.data > curr.next.data) || (ind == 1 && curr.data < curr.next.data)) { if (res == null) res = curr.next; // Store new next element of current // node next = curr.next.next; // Previous node of current node will // now point to next node of current node if (prev != null) prev.next = curr.next; // Change next pointers of both // adjacent nodes curr.next.next = curr; curr.next = next; // Change previous pointer. if (prev != null) prev = prev.next; else prev = res; } // If already in zig zag form, then move // to next element. else { if (res == null) { res = curr; } prev = curr; curr = curr.next; } // Update info whether next element should // be less than or greater than. ind = 1 - ind; } return res; } /* UTILITY FUNCTIONS */ /* Function to push a Node */ 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; head = head_ref; } /* Function to print linked list */ function printList(Node) { while (Node != null) { document.write(Node.data + "->"); Node = Node.next; } } // Driver Code /* Start with the empty list */ head = null; // Create a list 4 -> 3 -> 7 -> 8 -> 6 -> 2 -> 1 // answer should be -> 3 7 4 8 2 6 1 push(head, 1); push(head, 2); push(head, 6); push(head, 8); push(head, 7); push(head, 3); push(head, 4); document.write("Given linked list <br>"); printList(head); head = zigZagList(head); document.write("<br>Zig Zag Linked list <br>"); printList(head); // This code is contributed by rdtank </script>
Given linked list 4->3->7->8->6->2->1-> Zig Zag Linked list 3->7->4->8->2->6->1->
Complejidad temporal: O(N)
Espacio auxiliar: O(1)