Open In App

Convert a Linked List to Peak list

Last Updated : 28 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a linked list, rearrange the nodes so all the even nodes are peak. Peak nodes are those nodes that have greater value than the surrounding nodes. All the nodes of the Linked List have unique values.

Examples:

Input: 2->4->1->9->5->3
Output: 1->3->2->5->4->9
Explanation: All the node values at even positions 3 are greater than 2,1, and 5 are greater than 2,4, and 9 is greater than 4, so all even-positioned nodes are greater than the values of the surrounding nodes.

Input: 1->2->3->4
Output: 1->3->2->4
Explanation: All the node’s values at even positions are greater than the values of the surrounding nodes.

Approach: To solve the problem follow the below idea:

This problem can be solved using greedy by sorting the linked list and then to make the even elements as peaks we swap the node at even position to the node next to it of sorted linked list.

Follow the given steps to solve the problem:

  • Initialize the cnt = 1 to keep checking whether the node position is even or not.
  • Assign the head variable to the temp node
  • Traverse the linked list while temp->next is not NULL
  • If even positioned node is found swap its value with the next node which becomes the peak
  • Move the temp pointer to the next node and increment the cnt
  • Return the head

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
// Strucure the node
struct Node {
    int data;
    struct Node* next;
    Node(int x)
    {
        data = x;
        next = NULL;
    }
};
 
Node* merge(Node* firstNode, Node* secondNode)
{
    Node* merged = new Node(-1);
    Node* temp = new Node(-1);
 
    // Merged is equal to temp so in the end
    // we have the top Node.
    merged = temp;
 
    // While either firstNode or
    // secondNode becomes NULL
    while (firstNode != NULL && secondNode != NULL) {
 
        if (firstNode->data <= secondNode->data) {
            temp->next = firstNode;
            firstNode = firstNode->next;
        }
 
        else {
            temp->next = secondNode;
            secondNode = secondNode->next;
        }
        temp = temp->next;
    }
 
    // Any remaining Node in firstNode or
    // secondNode gets inserted in the temp List
    while (firstNode != NULL) {
        temp->next = firstNode;
        firstNode = firstNode->next;
        temp = temp->next;
    }
 
    while (secondNode != NULL) {
        temp->next = secondNode;
        secondNode = secondNode->next;
        temp = temp->next;
    }
 
    // Return the head of the sorted list
    return merged->next;
}
 
// Function to calculate the middle Element
Node* middle(Node* head)
{
    Node* slow = head;
    Node* fast = head->next;
 
    while (!slow->next && (!fast && !fast->next)) {
        slow = slow->next;
        fast = fast->next->next;
    }
    return slow;
}
 
// Function to sort the given linked
// list using Merge Sort.
Node* mergeSort(Node* head)
{
    // your code here
    if (head->next == NULL) {
        return head;
    }
 
    Node* mid = new Node(-1);
    Node* head2 = new Node(-1);
    mid = middle(head);
    head2 = mid->next;
    mid->next = NULL;
 
    Node* finalhead
        = merge(mergeSort(head), mergeSort(head2));
    return finalhead;
}
 
Node* rearrangeWithPeaks(Node* head)
{
 
    // Intialize the cnt = 1 to keep check the
    // node position is even or not
    int cnt = 1;
 
    // Assign the head variable to temp node
    Node* temp = head;
    // Traverse the linked list while
    // temp->next is not NULL
    while (temp->next != NULL) {
 
        // If even positioned node is found swap
        // its value with the next node which
        // becomes the peak
        if (cnt % 2 == 0) {
            swap(temp->data, temp->next->data);
        }
        // Move temp pointer to the next node
        // and increment the count
        temp = temp->next;
        cnt++;
    }
    // Return the head
    return head;
}
void printList(Node* node)
{
    while (node != NULL) {
        printf("%d ", node->data);
        node = node->next;
    }
    printf("\n");
}
 
// Driver code
int main()
{
    // Linked list
    Node* head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(3);
    head->next->next->next = new Node(4);
    head->next->next->next->next = new Node(5);
    cout << "Before rearranging: ";
    printList(head);
    mergeSort(head);
    cout << "After rearranging: ";
    rearrangeWithPeaks(head);
    printList(head);
 
    return 0;
}


Java




class Node {
    int data;
    Node next;
 
    Node(int x) {
        data = x;
        next = null;
    }
}
 
public class LinkedList {
 
    Node merge(Node firstNode, Node secondNode) {
        Node merged = new Node(-1);
        Node temp = merged;
 
        while (firstNode != null && secondNode != null) {
            if (firstNode.data <= secondNode.data) {
                temp.next = firstNode;
                firstNode = firstNode.next;
            } else {
                temp.next = secondNode;
                secondNode = secondNode.next;
            }
            temp = temp.next;
        }
 
        while (firstNode != null) {
            temp.next = firstNode;
            firstNode = firstNode.next;
            temp = temp.next;
        }
 
        while (secondNode != null) {
            temp.next = secondNode;
            secondNode = secondNode.next;
            temp = temp.next;
        }
 
        return merged.next;
    }
 
    Node middle(Node head) {
        Node slow = head;
        Node fast = head.next;
 
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
 
    Node mergeSort(Node head) {
        if (head == null || head.next == null) {
            return head;
        }
 
        Node mid = middle(head);
        Node head2 = mid.next;
        mid.next = null;
 
        Node finalHead = merge(mergeSort(head), mergeSort(head2));
        return finalHead;
    }
 
    Node rearrangeWithPeaks(Node head) {
        int cnt = 1;
        Node temp = head;
 
        while (temp != null && temp.next != null) {
            if (cnt % 2 == 0) {
                int tempData = temp.data;
                temp.data = temp.next.data;
                temp.next.data = tempData;
            }
            temp = temp.next;
            cnt++;
        }
        return head;
    }
 
    void printList(Node node) {
        while (node != null) {
            System.out.print(node.data + " ");
            node = node.next;
        }
        System.out.println();
    }
 
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5);
 
        System.out.print("Before rearranging: ");
        list.printList(head);
 
        head = list.mergeSort(head);
        System.out.print("After merge sort: ");
        list.printList(head);
 
        head = list.rearrangeWithPeaks(head);
        System.out.print("After rearranging with peaks: ");
        list.printList(head);
    }
}


Python3




# Define the structure of a node
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None
 
# Merge two sorted linked lists
def merge(firstNode, secondNode):
    merged = Node(-1)
    temp = Node(-1)
    merged = temp
 
    while firstNode and secondNode:
        if firstNode.data <= secondNode.data:
            temp.next = firstNode
            firstNode = firstNode.next
        else:
            temp.next = secondNode
            secondNode = secondNode.next
        temp = temp.next
 
    while firstNode:
        temp.next = firstNode
        firstNode = firstNode.next
        temp = temp.next
 
    while secondNode:
        temp.next = secondNode
        secondNode = secondNode.next
        temp = temp.next
 
    return merged.next
 
# Find the middle element of the linked list
def middle(head):
    slow = head
    fast = head.next
 
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
    return slow
 
# Sort the linked list using merge sort
def mergeSort(head):
    if not head or not head.next:
        return head
 
    mid = middle(head)
    head2 = mid.next
    mid.next = None
 
    return merge(mergeSort(head), mergeSort(head2))
 
# Rearrange the nodes in such a way that the even position nodes have higher values
def rearrangeWithPeaks(head):
    cnt = 1
    temp = head
 
    while temp and temp.next:
        if cnt % 2 == 0:
            temp.data, temp.next.data = temp.next.data, temp.data
        temp = temp.next
        cnt += 1
 
    return head
 
# Print the linked list
def printList(node):
    while node:
        print(node.data, end=" ")
        node = node.next
    print()
 
# Driver code
if __name__ == "__main__":
    # Create a linked list
    head = Node(1)
    head.next = Node(2)
    head.next.next = Node(3)
    head.next.next.next = Node(4)
    head.next.next.next.next = Node(5)
 
    print("Before rearranging: ", end="")
    printList(head)
 
    # Sort and rearrange the linked list
    head = mergeSort(head)
 
    print("After rearranging: ", end="")
    head = rearrangeWithPeaks(head)
    printList(head)


C#




using System;
 
// Node structure
public class Node
{
    public int data;
    public Node next;
 
    public Node(int x)
    {
        data = x;
        next = null;
    }
}
 
public class LinkedListMergeSort
{
    // Merge function
    public Node Merge(Node firstNode, Node secondNode)
    {
        Node merged = new Node(-1);
        Node temp = new Node(-1);
 
        // Merged is equal to temp so in the end
        // we have the top Node.
        merged = temp;
 
        // While either firstNode or
        // secondNode becomes NULL
        while (firstNode != null && secondNode != null)
        {
            if (firstNode.data <= secondNode.data)
            {
                temp.next = firstNode;
                firstNode = firstNode.next;
            }
            else
            {
                temp.next = secondNode;
                secondNode = secondNode.next;
            }
            temp = temp.next;
        }
 
        // Any remaining Node in firstNode or
        // secondNode gets inserted in the temp List
        while (firstNode != null)
        {
            temp.next = firstNode;
            firstNode = firstNode.next;
            temp = temp.next;
        }
 
        while (secondNode != null)
        {
            temp.next = secondNode;
            secondNode = secondNode.next;
            temp = temp.next;
        }
 
        // Return the head of the sorted list
        return merged.next;
    }
 
    // Function to calculate the middle Element
    public Node Middle(Node head)
    {
        Node slow = head;
        Node fast = head?.next;
 
        while (slow?.next != null && (fast != null && fast.next != null))
        {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
 
    // Function to sort the given linked
    // list using Merge Sort
    public Node MergeSort(Node head)
    {
        if (head?.next == null)
        {
            return head;
        }
 
        Node mid = new Node(-1);
        Node head2 = new Node(-1);
        mid = Middle(head);
        head2 = mid?.next;
        mid.next = null;
 
        Node finalhead = Merge(MergeSort(head), MergeSort(head2));
        return finalhead;
    }
 
    // Rearrange with peaks function
    public Node RearrangeWithPeaks(Node head)
    {
        // Intialize the cnt = 1 to keep check the
        // node position is even or not
        int cnt = 1;
        // Assign the head variable to temp node
        Node temp = head;
 
        // Traverse the linked list while
        // temp->next is not NULL
        while (temp?.next != null)
        {
            // If even positioned node is found swap
            // its value with the next node which
            // becomes the peak
            if (cnt % 2 == 0)
            {
                int tempData = temp.data;
                temp.data = temp.next.data;
                temp.next.data = tempData;
            }
            // Move temp pointer to the next node
            // and increment the count
            temp = temp.next;
            cnt++;
        }
        // Return the head
        return head;
    }
 
    // Print function
    public void PrintList(Node node)
    {
        while (node != null)
        {
            Console.Write(node.data + " ");
            node = node.next;
        }
        Console.WriteLine();
    }
 
    // Main method
    public static void Main(string[] args)
    {
        LinkedListMergeSort l = new LinkedListMergeSort();
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5);
 
        Console.Write("Before rearranging: ");
        l.PrintList(head);
 
        head = l.MergeSort(head);
        Console.Write("After rearranging: ");
        l.RearrangeWithPeaks(head);
        l.PrintList(head);
    }
}


Javascript




// Strucure the node
class Node {
    constructor(x) {
        this.data = x;
        this.next = null;
    }
}
 
function merge(firstNode, secondNode)
{
    let merged = new Node(-1);
    let temp = new Node(-1);
   
    // Merged is equal to temp so in the end
    // we have the top Node.
    merged = temp;
    // While either firstNode or
    // secondNode becomes NULL
    while (firstNode !== null && secondNode !== null) {
        if (firstNode.data <= secondNode.data) {
            temp.next = firstNode;
            firstNode = firstNode.next;
        }
        else {
            temp.next = secondNode;
            secondNode = secondNode.next;
        }
        temp = temp.next;
    }
    // Any remaining Node in firstNode or
    // secondNode gets inserted in the temp List
    while (firstNode !== null) {
        temp.next = firstNode;
        firstNode = firstNode.next;
        temp = temp.next;
    }
 
    while (secondNode !== null) {
        temp.next = secondNode;
        secondNode = secondNode.next;
        temp = temp.next;
    }
    // Return the head of the sorted list
    return merged.next;
}
// Function to calculate the middle Element
function middle(head)
{
    let slow = head;
    let fast = head.next;
 
    while (slow.next && fast && fast.next) {
        slow = slow.next;
        fast = fast.next.next;
    }
 
    return slow;
}
// Function to sort the given linked
// list using Merge Sort.
function mergeSort(head)
{
    // your code here
    if (head.next === null) {
        return head;
    }
 
    let mid = middle(head);
    let head2 = mid.next;
    mid.next = null;
 
    let finalhead = merge(mergeSort(head), mergeSort(head2));
    return finalhead;
}
 
function rearrangeWithPeaks(head)
{
    // Intialize the cnt = 1 to keep check the
    // node position is even or not
    let cnt = 1;
   
    // Assign the head variable to temp node
    let temp = head;
    // Traverse the linked list while
    // temp->next is not NULL
    while (temp.next !== null) {
       
        // If even positioned node is found swap
        // its value with the next node which
        // becomes the peak
        if (cnt % 2 === 0) {
            [temp.data, temp.next.data] = [temp.next.data, temp.data];
        }
     
        // Move temp pointer to the next node
        // and increment the count
        temp = temp.next;
        cnt++;
    }
    // Return the head
    return head;
}
 
function printList(node)
{
    let output = '';
    while (node !== null) {
        output += node.data + ' ';
        node = node.next;
    }
    console.log(output);
}
 
// Driver code
 
// Linked list
let head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
 
console.log("Before rearranging:");
printList(head);
head = mergeSort(head);
console.log("After rearranging:");
head = rearrangeWithPeaks(head);
printList(head);


Output

Before rearranging: 1 2 3 4 5 
After rearranging: 1 3 2 5 4 






Time Complexity: O(N*log N) where N is the size of the linked list.
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads