Program to unfold a folded linked list
Last Updated :
08 Jul, 2022
A linked list L0 -> L1 -> L2 -> ..... -> LN can be folded as L0 -> LN -> L1 -> LN - 1 -> L2 -> .....
Given a folded linked list, the task is to unfold and print the original linked list
Examples:
Input: 1 -> 6 -> 2 -> 5 -> 3 -> 4
Output: 1 2 3 4 5 6
Input: 1 -> 5 -> 2 -> 4 -> 3
Output: 1 2 3 4 5
Approach: Make a recursive call and store the next node in temp pointer, first node will act as head node and the node which is stored in temp pointer will act as a tail of the list. On returning after reaching the base condition link the head and tail to previous head and tail respectively.
Base condition: If number of nodes is even then the second last node is head and the last node is tail and if the number of nodes is odd then last node will act as head as well as tail.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include<bits/stdc++.h>
using namespace std;
// Node Class
struct Node
{
int data;
Node *next;
};
// Head of the list
Node *head;
// Tail of the list
Node *tail;
// Function to print the list
void display()
{
if (head == NULL)
return;
Node* temp = head;
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
// Function to add node in the list
void push(int data)
{
// Create new node
Node* nn = new Node();
nn->data = data;
nn->next = NULL;
// Linking at first position
if (head == NULL)
{
head = nn;
}
else
{
Node* temp = head;
while (temp->next != NULL)
{
temp = temp->next;
}
// Linking at last in list
temp->next = nn;
}
}
// Function to unfold the given link list
void unfold(Node* node)
{
if (node == NULL)
return;
// This condition will reach if
// the number of nodes is odd
// head and tail is same i->e-> last node
if (node->next == NULL)
{
head = tail = node;
return;
}
// This base condition will reach if
// the number of nodes is even
// mark head to the second last node
// and tail to the last node
else if (node->next->next == NULL)
{
head = node;
tail = node->next;
return;
}
// Storing next node in temp pointer
// before making the recursive call
Node* temp = node->next;
// Recursive call
unfold(node->next->next);
// Connecting first node to head
// and mark it as a new head
node->next = head;
head = node;
// Connecting tail to second node (temp)
// and mark it as a new tail
tail->next = temp;
tail = temp;
tail->next = NULL;
}
// Driver code
int main()
{
// Adding nodes to the list
push(1);
push(5);
push(2);
push(4);
push(3);
// Displaying the original nodes
display();
// Calling unfold function
unfold(head);
// Displaying the list
// after modification
display();
}
// This code is contributed by pratham76
Java
// Java implementation of the approach
public class GFG {
// Node Class
private class Node {
int data;
Node next;
}
// Head of the list
private Node head;
// Tail of the list
private Node tail;
// Function to print the list
public void display()
{
if (head == null)
return;
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
// Function to add node in the list
public void push(int data)
{
// Create new node
Node nn = new Node();
nn.data = data;
nn.next = null;
// Linking at first position
if (head == null) {
head = nn;
}
else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
// Linking at last in list
temp.next = nn;
}
}
// Function to unfold the given link list
private void unfold(Node node)
{
if (node == null)
return;
// This condition will reach if
// the number of nodes is odd
// head and tail is same i.e. last node
if (node.next == null) {
head = tail = node;
return;
}
// This base condition will reach if
// the number of nodes is even
// mark head to the second last node
// and tail to the last node
else if (node.next.next == null) {
head = node;
tail = node.next;
return;
}
// Storing next node in temp pointer
// before making the recursive call
Node temp = node.next;
// Recursive call
unfold(node.next.next);
// Connecting first node to head
// and mark it as a new head
node.next = head;
head = node;
// Connecting tail to second node (temp)
// and mark it as a new tail
tail.next = temp;
tail = temp;
tail.next = null;
}
// Driver code
public static void main(String[] args)
{
GFG l = new GFG();
// Adding nodes to the list
l.push(1);
l.push(5);
l.push(2);
l.push(4);
l.push(3);
// Displaying the original nodes
l.display();
// Calling unfold function
l.unfold(l.head);
// Displaying the list
// after modification
l.display();
}
}
Python3
# Python3 implementation of the approach
# Node Class
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Head of the list
head = None
# Tail of the list
tail = None
# Function to print the list
def display():
if (head == None):
return
temp = head
while (temp != None):
print(temp.data, end = " ")
temp = temp.next
print()
# Function to add node in the list
def push(data):
global head, tail
# Create new node
nn = Node(data)
# Linking at first position
if (head == None):
head = nn
else:
temp = head
while (temp.next != None):
temp = temp.next
# Linking at last in list
temp.next = nn
# Function to unfold the given link list
def unfold(node):
global head, tail
if (node == None):
return
# This condition will reach if
# the number of nodes is odd
# head and tail is same i.e. last node
if (node.next == None):
head = tail = node
return
# This base condition will reach if
# the number of nodes is even
# mark head to the second last node
# and tail to the last node
elif (node.next.next == None):
head = node
tail = node.next
return
# Storing next node in temp pointer
# before making the recursive call
temp = node.next
# Recursive call
unfold(node.next.next)
# Connecting first node to head
# and mark it as a new head
node.next = head
head = node
# Connecting tail to second node (temp)
# and mark it as a new tail
tail.next = temp
tail = temp
tail.next = None
# Driver code
if __name__=='__main__':
# Adding nodes to the list
push(1)
push(5)
push(2)
push(4)
push(3)
# Displaying the original nodes
display()
# Calling unfold function
unfold(head)
# Displaying the list
# after modification
display()
# This code is contributed by rutvik_56
C#
// C# implementation of the approach
using System;
public class GFG {
// Node Class
private class Node {
public int data;
public Node next;
}
// Head of the list
private Node head;
// Tail of the list
private Node tail;
// Function to print the list
public void display()
{
if (head == null)
return;
Node temp = head;
while (temp != null) {
Console.Write(temp.data + " ");
temp = temp.next;
}
Console.WriteLine();
}
// Function to add node in the list
public void push(int data)
{
// Create new node
Node nn = new Node();
nn.data = data;
nn.next = null;
// Linking at first position
if (head == null) {
head = nn;
}
else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
// Linking at last in list
temp.next = nn;
}
}
// Function to unfold the given link list
private void unfold(Node node)
{
if (node == null)
return;
// This condition will reach if
// the number of nodes is odd
// head and tail is same i.e. last node
if (node.next == null) {
head = tail = node;
return;
}
// This base condition will reach if
// the number of nodes is even
// mark head to the second last node
// and tail to the last node
else if (node.next.next == null) {
head = node;
tail = node.next;
return;
}
// Storing next node in temp pointer
// before making the recursive call
Node temp = node.next;
// Recursive call
unfold(node.next.next);
// Connecting first node to head
// and mark it as a new head
node.next = head;
head = node;
// Connecting tail to second node (temp)
// and mark it as a new tail
tail.next = temp;
tail = temp;
tail.next = null;
}
// Driver code
public static void Main()
{
GFG l = new GFG();
// Adding nodes to the list
l.push(1);
l.push(5);
l.push(2);
l.push(4);
l.push(3);
// Displaying the original nodes
l.display();
// Calling unfold function
l.unfold(l.head);
// Displaying the list
// after modification
l.display();
}
}
/* This code contributed by PrinciRaj1992 */
JavaScript
<script>
// Javascript implementation of the approach
// Represents node of the linked list
class Node {
constructor() {
this.data = 0;
this.next = null;
}
}
// Head of the list
var head = null;
// Tail of the list
var tail = null;
// Function to print the list
function display()
{
if (head == null)
return;
var temp = head;
while (temp != null) {
document.write(temp.data + " ");
temp = temp.next;
}
document.write("</br>");
}
// Function to add node in the list
function push( data)
{
// Create new node
var nn = new Node();
nn.data = data;
nn.next = null;
// Linking at first position
if (head == null) {
head = nn;
}
else {
var temp = head;
while (temp.next != null) {
temp = temp.next;
}
// Linking at last in list
temp.next = nn;
}
}
// Function to unfold the given link list
function unfold( node)
{
if (node == null)
return;
// This condition will reach if
// the number of nodes is odd
// head and tail is same i.e. last node
if (node.next == null) {
head = tail = node;
return;
}
// This base condition will reach if
// the number of nodes is even
// mark head to the second last node
// and tail to the last node
else if (node.next.next == null) {
head = node;
tail = node.next;
return;
}
// Storing next node in temp pointer
// before making the recursive call
var temp = node.next;
// Recursive call
unfold(node.next.next);
// Connecting first node to head
// and mark it as a new head
node.next = head;
head = node;
// Connecting tail to second node (temp)
// and mark it as a new tail
tail.next = temp;
tail = temp;
tail.next = null;
}
// Driver Code
// Adding nodes to the list
push(1);
push(5);
push(2);
push(4);
push(3);
// Displaying the original nodes
display();
// Calling unfold function
unfold(head);
// Displaying the list
// after modification
display();
// This code is contributed by jana_sayantan.
</script>
Output1 5 2 4 3
1 2 3 4 5
Time Complexity: O(N), where N is the total number of nodes in the linked list.
Auxiliary Space: O(N)
Iterative Approach:-
Approach: First we have to segregate the linked list on the basis of even-odd index. Then we reverse the odd part of segregated list and joined with the first list. This approach does not use recursive space.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <iostream>
using namespace std;
class ListNode {
public:
int val = 0;
ListNode* next = nullptr;
ListNode(int val) { this->val = val; }
};
ListNode* reverse(ListNode* head)
{
ListNode *prev = NULL, *temp = head, *copy = NULL;
while (temp != NULL) {
copy = temp->next;
temp->next = prev;
prev = temp;
temp = copy;
}
return prev;
}
void unfold(ListNode* head)
{
// for segregating the original linked list into two
// linked list on the basis of even and odd
int i = 0;
// For storing the previous node
// and head node for each linked list
ListNode *prev1 = NULL, *prev2 = NULL, *h1 = head,
*h2 = head;
while (head != NULL) {
if (i % 2 == 0) {
if (prev1 == NULL) {
h1 = head;
prev1 = head;
}
else {
prev1->next = head;
prev1 = head;
}
}
else {
if (prev2 == NULL) {
h2 = head;
prev2 = head;
}
else {
prev2->next = head;
prev2 = head;
}
}
i++;
head = head->next;
}
prev2->next = NULL;
ListNode* rev
= reverse(h2); // reverse the second linked list
prev1->next = rev; // join the first ll with second one
}
void printList(ListNode* node)
{
ListNode* curr = node;
while (curr != nullptr) {
cout << curr->val << " ";
curr = curr->next;
}
cout << endl;
}
int main()
{
int n;
ListNode* dummy = new ListNode(-1);
ListNode* prev = dummy;
n=5;int i=0;
int arr[]={1, 5, 2, 4, 3}; //Elements in the linkedlist
while (i < n) {
prev->next = new ListNode(arr[i]);
prev = prev->next;
i++;
}
ListNode* head = dummy->next;
printList(head);
unfold(head);
printList(head);
return 0;
}
// This code is contributed by Ankit
Java
// Java implementation of the approach
class GFG {
static class ListNode {
int val = 0;
ListNode next = null;
ListNode(int val) { this.val = val; }
}
static ListNode reverse(ListNode head)
{
ListNode prev = null, temp = head, copy = null;
while (temp != null) {
copy = temp.next;
temp.next = prev;
prev = temp;
temp = copy;
}
return prev;
}
static void unfold(ListNode head)
{
// for segregating the original linked list into two
// linked list on the basis of even and odd
int i = 0;
// For storing the previous node
// and head node for each linked list
ListNode prev1 = null, prev2 = null, h1 = head,
h2 = head;
while (head != null) {
if (i % 2 == 0) {
if (prev1 == null) {
h1 = head;
prev1 = head;
}
else {
prev1.next = head;
prev1 = head;
}
}
else {
if (prev2 == null) {
h2 = head;
prev2 = head;
}
else {
prev2.next = head;
prev2 = head;
}
}
i++;
head = head.next;
}
prev2.next = null;
ListNode rev
= reverse(h2); // reverse the second linked list
prev1.next
= rev; // join the first ll with second one
}
static void printList(ListNode node)
{
ListNode curr = node;
while (curr != null) {
System.out.print(curr.val + " ");
curr = curr.next;
}
System.out.println();
}
public static void main(String[] args)
{
int n;
ListNode dummy = new ListNode(-1);
ListNode prev = dummy;
n = 5;
int i = 0;
int arr[] = { 1, 5, 2, 4,
3 }; // Elements in the linkedlist
while (i < n) {
prev.next = new ListNode(arr[i]);
prev = prev.next;
i++;
}
ListNode head = dummy.next;
printList(head);
unfold(head);
printList(head);
}
}
// This code is contributed by Lovely Jain
Python3
# Python code to implement the above approach
class ListNode:
def __init__(self,val):
self.next = None
self.val = val
def reverse(head):
prev,temp,copy = None,head,None
while (temp != None):
copy = temp.next
temp.next = prev
prev = temp
temp = copy
return prev
def unfold(head):
# for segregating the original linked list into two
# linked list on the basis of even and odd
i = 0
# For storing the previous node
# and head node for each linked list
prev1,prev2,h1,h2 = None,None,head,head
while (head != None):
if (i % 2 == 0):
if (prev1 == None):
h1 = head
prev1 = head
else :
prev1.next = head
prev1 = head
else:
if (prev2 == None):
h2 = head
prev2 = head
else:
prev2.next = head
prev2 = head
i += 1
head = head.next
prev2.next = None
rev = reverse(h2) # reverse the second linked list
prev1.next = rev # join the first ll with second one
def printList(node):
curr = node
while (curr != None):
print(curr.val,end = " ")
curr = curr.next
print()
# driver code
dummy = ListNode(-1)
prev = dummy
n=5
i=0
arr = [1, 5, 2, 4, 3] #Elements in the linkedlist
while (i < n):
prev.next = ListNode(arr[i])
prev = prev.next
i += 1
head = dummy.next
printList(head)
unfold(head)
printList(head)
# this code is contributed by shinjanpatra
C#
// C# implementation of the approach
using System;
class GFG {
class ListNode {
public int val = 0;
public ListNode next = null;
public ListNode(int val) { this.val = val; }
}
static ListNode reverse(ListNode head)
{
ListNode prev = null, temp = head, copy = null;
while (temp != null) {
copy = temp.next;
temp.next = prev;
prev = temp;
temp = copy;
}
return prev;
}
static void unfold(ListNode head)
{
// for segregating the original linked list into two
// linked list on the basis of even and odd
int i = 0;
// For storing the previous node and head node for
// each linked list.
ListNode prev1 = null, prev2 = null, h2 = head;
while (head != null) {
if (i % 2 == 0) {
if (prev1 == null) {
prev1 = head;
}
else {
prev1.next = head;
prev1 = head;
}
}
else {
if (prev2 == null) {
h2 = head;
prev2 = head;
}
else {
prev2.next = head;
prev2 = head;
}
}
i++;
head = head.next;
}
prev2.next = null;
ListNode rev = reverse(
h2); // reverse the second linked list.
prev1.next = rev; // join the first linked list with
// second one.
}
static void printList(ListNode node)
{
ListNode curr = node;
while (curr != null) {
Console.Write(curr.val + " ");
curr = curr.next;
}
Console.WriteLine();
}
static public void Main()
{
// Code
int n;
ListNode dummy = new ListNode(-1);
ListNode prev = dummy;
n = 5;
int i = 0;
int[] arr = { 1, 5, 2, 4,
3 }; // Elements in the linked list.
while (i < n) {
prev.next = new ListNode(arr[i]);
prev = prev.next;
i++;
}
ListNode head = dummy.next;
printList(head);
unfold(head);
printList(head);
}
}
// This code is contributed by lokesh (lokeshmvs21).
JavaScript
<script>
// JavaScript code to implement the above approach
class ListNode {
constructor(val){
this.next = null;
this.val = val;
}
}
function reverse(head)
{
let prev = null, temp = head, copy = null;
while (temp != null) {
copy = temp.next;
temp.next = prev;
prev = temp;
temp = copy;
}
return prev;
}
function unfold(head)
{
// for segregating the original linked list into two
// linked list on the basis of even and odd
let i = 0;
// For storing the previous node
// and head node for each linked list
let prev1 = null, prev2 = null, h1 = head,h2 = head;
while (head != null) {
if (i % 2 == 0) {
if (prev1 == null) {
h1 = head;
prev1 = head;
}
else {
prev1.next = head;
prev1 = head;
}
}
else {
if (prev2 == null) {
h2 = head;
prev2 = head;
}
else {
prev2.next = head;
prev2 = head;
}
}
i++;
head = head.next;
}
prev2.next = null;
let rev = reverse(h2); // reverse the second linked list
prev1.next = rev; // join the first ll with second one
}
function printList(node)
{
let curr = node;
while (curr != null) {
document.write(curr.val," ");
curr = curr.next;
}
document.write("</br>");
}
// driver code
let n;
let dummy = new ListNode(-1);
let prev = dummy;
n=5;
let i=0;
let arr = [1, 5, 2, 4, 3]; //Elements in the linkedlist
while (i < n) {
prev.next = new ListNode(arr[i]);
prev = prev.next;
i++;
}
let head = dummy.next;
printList(head);
unfold(head);
printList(head);
// This code is contributed by shinjanpatra
</script>
Output1 5 2 4 3
1 2 3 4 5
Time Complexity: O(N), where N is the total number of nodes in the linked list.
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem