C++ program to fold a linked list

Fold a linked list in C++

How to fold a linked list?

Folding a linked list is like joining the two end of the linked list, and merging them together. In this article, we will learn that what does Folding a Linked List means, and what steps and algorithm we need to follow to perform the following task. Let’s see how to code a C++ Program for folding a Linked List.

Folding helps in rearranging the linked list in a symmetric way where the first element links with the last, the second with the second last, and so on. This technique is useful for optimizing specific operations or achieving alternate traversal patterns.

Steps to write a C++ program to fold a linked list

To fold a linked list following steps are followed

  1. Define the linked list.
  2. In the main method call all the method you have declared with input/output statement you want to use.
  3. In the method fold multiple process are going on.
  4. First we are finding middle of the linked using slow and fast pointer trick.
  5. Now we will divide the linked list into two half
  6. Second we are reversing the linked list from middle to tail i.e. second half of the list.
  7. Later we will print each element of both the list one by one.

How to construct a linked list ?

class Node  

    int data; 
    Node *next; 
}; 
Fold a Linked List in C++

Algorithm to fold a linked list in C++

  1. WHILE(HEAD1||HEAD2)
  2. IF(HEAD1)
  3. CURR->NEXT=HEAD1
  4. CURR=CURR->NEXT
  5. HEAD1=HEAD1->NEXT
  6. END IF
  7. IF(HEAD2)
  8. CURR->NEXT=HEAD2
  9. CURR=CURR->NEXT
  10. HEAD2=HEAD2->NEXT
  11. END IF  & WHILE
  12. HEAD=HEAD->NEXT

Program to fold a linked list in C++

A program to fold a linked list in C++ rearranges the nodes so that the first and last elements come together alternately. It efficiently modifies the linked list structure using pointer manipulation without extra space.

Run

#include<bits/stdc++.h>
using namespace std;
//constructing the structure of a node
struct node
{
  int data;
  struct node *next;
};
//declaring the prototype of the functions that we are going to use
void build (struct node **head, int data);
void display (struct node *head);
struct node *newNode (int data);
void fold (node ** head);
void reverselist (node ** head);

int main (void)			//main method.
{
  int n, k;
  cout<< "Enter size of linked list\n"; cin>>n;
  int data[100];
  cout << "Enter linked list data\n";
  for (int i = 0; i < n; i++) { cin >> data[i];
    }


  struct node *head = NULL;

  //constructing linked list
  for (int i = n - 1; i >= 0; i--)
    build (&head, data[i]);
  cout << "\nLinked List Data: ";
  display (head);

  fold (&head);
  cout << "\nLinked list after folding\nLinked List Data: "; display (head); return 0; } void build (struct node **head, int data) //fuction to build the linked list { struct node *newNode = (struct node *) malloc (sizeof (struct node)); newNode->data = data;
  newNode->next = *head;
  *head = newNode;
}

void display (struct node *head)	//displaying the linked List
{
  struct node *ptr = head;
  while (ptr)
    {
      cout << ptr->data << " "; ptr = ptr->next;
    }
}

struct node *newNode (int data)		//allocating memory to a new node(dummy node)
{
  struct node *newNode = (struct node *) malloc (sizeof (struct node));
  newNode->data = data;
  newNode->next = NULL;
  return newNode;
}

void fold (node ** head)		//function for rearranging the node
{

  node *slow = *head, *fast = slow->next;
  while (fast && fast->next)
    {
      slow = slow->next;
      fast = fast->next->next;
    }
  struct node *head1 = *head;
  struct node *head2 = slow->next;
  slow->next = NULL;		//slow pointer will be at middle position 

  reverselist (&head2);		//reversing second half of the list 


  *head = newNode (0);		// Assign dummy Node 

  node *curr = *head;
  while (head1 || head2)
    {
      if (head1)
	{
	  curr->next = head1;
	  curr = curr->next;
	  head1 = head1->next;
	}

      if (head2)
	{
	  curr->next = head2;
	  curr = curr->next;
	  head2 = head2->next;
	}
    }

  *head = (*head)->next;
}

//function for reversing the List
void reverselist (node ** head)
{
  node *prev = NULL, *curr = *head, *next;

  while (curr)
    {
      next = curr->next;
      curr->next = prev;
      prev = curr;
      curr = next;
    }

  *head = prev;
}

Output:

Enter size of linked list
5
Enter linked list data 
14
56
25
31
54

Linked List Data: 14 56 25 31 54 
Linked list after folding
Linked List Data: 14 54 56 31 25 

Explanation:

  • The program starts by defining a node structure containing an integer data field and a pointer to the next node, which helps in forming a linked list.
  • The build() function dynamically allocates memory and inserts each new node at the beginning, constructing the linked list from user input.
  • Using the slow and fast pointer technique, the fold() function identifies the middle of the list, effectively dividing it into two halves.
  • The second half of the linked list is reversed using the reverselist() function, preparing it for the folding operation.
  • Finally, nodes from the first and reversed second halves are alternately merged to create a folded linked list pattern, efficiently rearranging elements in O(n) time and O(1) space.

Time and Space Complexity:

Function Time Complexity Space Complexity
build() O(n) O(1)
display() O(n) O(1)
reverselist() O(n) O(1)
fold() O(n) O(1)
Overall O(n) O(1)

To wrap it up:

The code demonstrates a clean and effective method to “fold” a singly linked list by using the slow and fast pointer technique to split the list, reversing the second half, and then alternating nodes from both halves to create the new arrangement.

This approach runs in linear time and uses constant extra space, making it both time efficient and memory efficient ideal for large lists in resource constrained settings.

FAQs

Folding a linked list means rearranging it so that the last node comes after the first, the second last after the second, and so on, effectively merging both ends toward the center.

The time complexity is O(n) since we traverse the list once to find the middle and once to reverse and merge the halves.

No, folding a linked list requires O(1) extra space as it can be done in-place using pointer manipulation.

Yes, by reversing the second half again and rejoining it with the first half, you can restore the linked list to its original sequence.

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription

Singly Linked List

  • Introduction to Linked List in Data Structure
    Click Here
  • Linked List in –
    C | C++ | Java
  • Singly Linked List in –
    C | C++ | Java
  • Insertion in singly Linked List –
    C | C++ | Java
  • Insertion at beginning in singly Linked List  –
    C | C++Java
  • Insertion at nth position in singly Linked List  –
    C | C++Java
  • Insertion at end in singly Linked List  –
    C | C++Java
  • Deletion in singly Linked List  –
    C | C++Java
  • Deletion from beginning in singly linked list :
    C | C++ | Java
  • Deletion from nth position in singly linked list :
    C | C++ | Java
  • Deletion from end in singly linked list :
    C | C++ | Java
  • Linked List Insertion and Deletion –
    C | C++Java
  • Reverse a linked list without changing links between nodes (Data reverse only) –
    C | C++Java
  • Reverse a linked list by changing links between nodes –
    C | C++Java
  • Print reverse of a linked list without actually reversing –
    C |C++Java
  • Print reverse of a linked list without actually reversing –
    C |C++Java
  • Insertion in the middle Singly Linked List –
    C | C++Java
  • Insertion in a Sorted Linked List –
    C | C++Java
  • Delete alternate nodes of a Linked List –
    C | C++Java
  • Find middle of the linked list –
    C | C++Java
  • Reverse a linked list in groups of given size –
    C | C++Java
  • Find kth node from end of the linked list –
    C | C++Java
  • Append the last n nodes of a linked list to the beginning of the list –
    C | C++Java
  • Check whether linked list is palindrome or not –
    C | C++Java
  • Fold a Linked List –
    C | C++Java
  • Insert at given Position –
    C | C++Java
  • Deletion at given Position –
    C | C++Java

Singly Linked List

  • Introduction to Linked List in Data Structure
  • Linked List in – C | C++ | Java
  • Singly Linked List in – C | C++ | Java
  • Insertion in singly Linked List – C | C++ | Java
    • Insertion at beginning in singly Linked List  – C | C++Java
    • Insertion at nth position in singly Linked List  – C | C++Java
    • Insertion at end in singly Linked List  – C | C++Java
  • Deletion in singly Linked List  – C | C++Java
    • Deletion from beginning in singly linked list : C | C++ | Java
    • Deletion from nth position in singly linked list : C | C++ | Java
    • Deletion from end in singly linked list : C | C++ | Java
  • Reverse a linked list without changing links between nodes (Data reverse only) – C | C++Java
  • Linked List Insertion and Deletion – C | C++Java
  • Reverse a linked list by changing links between nodes – C | C++Java
  • Linked List insertion in the middle – C | C++Java
  • Print reverse of a linked list without actually reversing – C |C++ | Java
  • Search an element in a linked list – C | C++Java
  • Insertion in a Sorted Linked List – C | C++Java
  • Delete alternate nodes of a Linked List – C | C++Java
  • Find middle of the linked list – C | C++Java
  • Reverse a linked list in groups of given size – C | C++Java
  • Find kth node from end of the linked list – C | C++Java
  • Append the last n nodes of a linked list to the beginning of the list – C | C++Java
  • Check whether linked list is palindrome or not – C | C++Java
  • Fold a Linked List – C | C++Java
  • Insert at a given position – C | C++Java
  • Delete at a given position – C | C++Java