Convert a Linked List to Peak list
Last Updated :
28 Dec, 2023
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);
OutputBefore 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)
Similar Reads
Convert Singly Linked List to XOR Linked List
Prerequisite: XOR Linked List â A Memory Efficient Doubly Linked List | Set 1XOR Linked List â A Memory Efficient Doubly Linked List | Set 2 An XOR linked list is a memory efficient doubly linked list in which the next pointer of every node stores the XOR of previous and next node's address. Given a
9 min read
Linked List of Linked List
Linked list of linkeÂd list, also known as nested linkeÂd lists, is a type of Linked List where each main node stores another full linked list. This structure beats old, plain linked lists. It gives way more flexibility to store and manage compleÂx data. In this article we will learn about the bas
9 min read
Convert a Singly Linked List to an array
Given a singly linked list and the task is to convert it into an array.Examples: Input: List = 1 -> 2 -> 3 -> 4 -> NULL Output: 1 2 3 4Input: List = 10 -> 20 -> 30 -> 40 -> 50 -> NULL Output: 10 20 30 40 50 Approach:The idea is to iterate through the linked list and for ea
5 min read
XOR Linked List - Reversal of a List
Given a XOR linked list, the task is to reverse the XOR linked list. Examples: Input: 4 <â> 7 <â> 9 <â> 7Output: 7 <â> 9 <â> 7 <â> 4Explanation:Reversing the linked list modifies the XOR linked list to 7 <â> 9 <â> 7 <â> 4. Input: 2 <-> 5
12 min read
Concatenation of two Linked lists
Given two linked lists. The task is to concatenate the second list to the end of the first list.Examples:Input: list1: 10 -> 15 -> 4 -> 20, list2: 8 -> 4 -> 2 -> 10Output: 10 -> 15 -> 4 -> 20 -> 8 -> 4 -> 2 -> 10Input: list1: 1 -> 2 -> 3, list2: 4 -> 5
6 min read
Modify contents of Linked List
Given a Singly linked list. The task is to modify the value of the first half of nodes such that 1st node's new value is equal to the value of the last node minus the first node's current value, 2nd node's new value is equal to the second last node's value minus 2nd nodes current value, likewise for
15+ min read
Sort a Linked List in wave form
Given an unsorted Linked List of integers. The task is to sort the Linked List into a wave like Line. A Linked List is said to be sorted in Wave Form if the list after sorting is in the form: list[0] >= list[1] <= list[2] >= â¦.. Where list[i] denotes the data at i-th node of the Linked List
11 min read
Split a Circular Linked List into two halves
Given a Circular linked list. The task is split into two Circular Linked lists. If there are an odd number of nodes in the given circular linked list then out of the resulting two halved lists, the first list should have one node more than the second list.Examples:Input: 10->4->9Output: 10-
10 min read
Two-Pointer Technique in a Linked List
The two-pointer technique is a common technique used in linked list problems to solve a variety of problems efficiently. It involves using two pointers that traverse the linked list at different speeds or in different directions. Use Cases of Two-Pointer Technique in a Linked List:1. Finding the Mid
3 min read
First non-repeating in a linked list
Given a linked list, find its first non-repeating integer element. Examples: Input : 10->20->30->10->20->40->30->NULLOutput :First Non-repeating element is 40.Input :1->1->2->2->3->4->3->4->5->NULLOutput :First Non-repeating element is 5.Input :1->1
12 min read