Practice questions for Linked List and Recursion
Last Updated :
14 Feb, 2023
Assume the structure of a Linked List node is as follows.
C++
struct Node
{
int data;
struct Node *next;
};
// This code is contributed by SHUBHAMSINGH10
C
struct Node
{
int data;
struct Node *next;
};
Java
static class Node
{
int data;
Node next;
};
// This code is contributed by shubhamsingh10
Python3
class Node:
def __init__(self, data):
self.data = data
self.next = None
C#
public class Node
{
public int data;
public Node next;
};
// This code is contributed by pratham_76
JavaScript
<script>
class Node
{
constructor(item)
{
this.data = item;
this.next = null;
}
}
// This code contributed by shubhamsingh10
</script>
Explain the functionality of the following C functions.
1. What does the following function do for a given Linked List?
C++14
void fun1(struct Node* head)
{
if (head == NULL)
return;
fun1(head->next);
cout << head->data << " ";
}
// This code is contributed by shubhamsingh10
C
void fun1(struct Node* head)
{
if(head == NULL)
return;
fun1(head->next);
printf("%d ", head->data);
}
Java
static void fun1(Node head)
{
if (head == null)
{
return;
}
fun1(head.next);
System.out.print(head.data + " ");
}
// This code is contributed by shubhamsingh10
Python
def fun1(head):
if(head == None):
return
fun1(head.next)
print(head.data, end = " ")
# This code is contributed by shubhamsingh10
C#
static void fun1(Node head)
{
if (head == null)
{
return;
}
fun1(head.next);
Console.Write(head.data + " ");
}
// This code is contributed by shubhamsingh10
JavaScript
<script>
// Javascript Implementation
function fun1( head)
{
if (head == null)
return;
fun1(head.next);
document.write(head.data);
}
// This code is contributed by shubhamsingh10
</script>
fun1() prints the given Linked List in the reverse way. For Linked List 1->2->3->4->5, fun1() prints 5->4->3->2->1.
2. What does the following function do for a given Linked List?
C++
void fun2(struct Node* head)
{
if(head == NULL)
return;
cout << head->data << " ";
if(head->next != NULL )
fun2(head->next->next);
cout << head->data << " ";
}
// This code is contributed by shubhamsingh10
C
void fun2(struct Node* head)
{
if(head == NULL)
return;
printf("%d ", head->data);
if(head->next != NULL )
fun2(head->next->next);
printf("%d ", head->data);
}
Java
static void fun2(Node head)
{
if (head == null)
{
return;
}
System.out.print(head.data + " ");
if (head.next != null)
{
fun2(head.next.next);
}
System.out.print(head.data + " ");
}
// This code is contributed by shubhamsingh10
Python3
def fun2(head):
if(head == None):
return
print(head.data, end = " ")
if(head.next != None ):
fun2(head.next.next)
print(head.data, end = " ")
# This code is contributed by divyesh072019
C#
static void fun2(Node head)
{
if (head == null)
{
return;
}
Console.Write(head.data + " ");
if (head.next != null)
{
fun2(head.next.next);
}
Console.Write(head.data + " ");
}
// This code is contributed by divyeshrabadiya07
JavaScript
<script>
// Javascript Implementation
function fun2( head)
{
if (head == null)
return;
document.write(head.data);
if (head.next != null)
fun2(head.next.next);
document.write(head.data);
}
// This code is contributed by shubhamsingh10
</script>
fun2() prints alternate nodes of the given Linked List, first from head to end, and then from end to head. If Linked List has even number of nodes, then fun2() skips the last node. For Linked List 1->2->3->4->5, fun2() prints 1 3 5 5 3 1. For Linked List 1->2->3->4->5->6, fun2() prints 1 3 5 5 3 1.
Below is a complete running program to test the above functions.
C++
#include <bits/stdc++.h>
using namespace std;
/* A linked list node */
class Node
{
public:
int data;
Node *next;
};
/* Prints a linked list in reverse manner */
void fun1(Node* head)
{
if(head == NULL)
return;
fun1(head->next);
cout << head->data << " ";
}
/* prints alternate nodes of a Linked List, first
from head to end, and then from end to head. */
void fun2(Node* start)
{
if(start == NULL)
return;
cout<<start->data<<" ";
if(start->next != NULL )
fun2(start->next->next);
cout << start->data << " ";
}
/* UTILITY FUNCTIONS TO TEST fun1() and fun2() */
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
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 of the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Driver code */
int main()
{
/* Start with the empty list */
Node* head = NULL;
/* Using push() to construct below list
1->2->3->4->5 */
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
cout<<"Output of fun1() for list 1->2->3->4->5 \n";
fun1(head);
cout<<"\nOutput of fun2() for list 1->2->3->4->5 \n";
fun2(head);
return 0;
}
// This code is contributed by rathbhupendra
C
#include<stdio.h>
#include<stdlib.h>
/* A linked list node */
struct Node
{
int data;
struct Node *next;
};
/* Prints a linked list in reverse manner */
void fun1(struct Node* head)
{
if(head == NULL)
return;
fun1(head->next);
printf("%d ", head->data);
}
/* prints alternate nodes of a Linked List, first
from head to end, and then from end to head. */
void fun2(struct Node* start)
{
if(start == NULL)
return;
printf("%d ", start->data);
if(start->next != NULL )
fun2(start->next->next);
printf("%d ", start->data);
}
/* UTILITY FUNCTIONS TO TEST fun1() and fun2() */
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list of the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Driver program to test above functions */
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
/* Using push() to construct below list
1->2->3->4->5 */
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
printf("Output of fun1() for list 1->2->3->4->5 \n");
fun1(head);
printf("\nOutput of fun2() for list 1->2->3->4->5 \n");
fun2(head);
getchar();
return 0;
}
Java
// Java code implementation for above approach
class GFG
{
/* A linked list node */
static class Node
{
int data;
Node next;
};
/* Prints a linked list in reverse manner */
static void fun1(Node head)
{
if (head == null)
{
return;
}
fun1(head.next);
System.out.print(head.data + " ");
}
/* prints alternate nodes of a Linked List, first
from head to end, and then from end to head. */
static void fun2(Node start)
{
if (start == null)
{
return;
}
System.out.print(start.data + " ");
if (start.next != null)
{
fun2(start.next.next);
}
System.out.print(start.data + " ");
}
/* UTILITY FUNCTIONS TO TEST fun1() and fun2() */
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
static Node 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 of the new node */
new_node.next = (head_ref);
/* move the head to point to the new node */
(head_ref) = new_node;
return head_ref;
}
/* Driver code */
public static void main(String[] args)
{
/* Start with the empty list */
Node head = null;
/* Using push() to construct below list
1->2->3->4->5 */
head = push(head, 5);
head = push(head, 4);
head = push(head, 3);
head = push(head, 2);
head = push(head, 1);
System.out.print("Output of fun1() for " +
"list 1->2->3->4->5 \n");
fun1(head);
System.out.print("\nOutput of fun2() for " +
"list 1->2->3->4->5 \n");
fun2(head);
}
}
// This code is contributed by Rajput-Ji
Python3
''' A linked list node '''
class Node:
def __init__(self, data):
self.data = data
self.next = None
''' Prints a linked list in reverse manner '''
def fun1(head):
if(head == None):
return
fun1(head.next)
print(head.data, end = " ")
''' prints alternate nodes of a Linked List, first
from head to end, and then from end to head. '''
def fun2(start):
if(start == None):
return
print(start.data, end = " ")
if(start.next != None ):
fun2(start.next.next)
print(start.data, end = " ")
''' UTILITY FUNCTIONS TO TEST fun1() and fun2() '''
''' Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. '''
def push( head, new_data):
''' put in the data '''
new_node = Node(new_data)
''' link the old list of the new node '''
new_node.next = head
''' move the head to point to the new node '''
head = new_node
return head
''' Driver code '''
''' Start with the empty list '''
head = None
''' Using push() to construct below list
1.2.3.4.5 '''
head = Node(5)
head = push(head, 4)
head = push(head, 3)
head = push(head, 2)
head = push(head, 1)
print("Output of fun1() for list 1->2->3->4->5")
fun1(head)
print("\nOutput of fun2() for list 1->2->3->4->5")
fun2(head)
# This code is contributed by SHUBHAMSINGH10
C#
// C# code implementation for above approach
using System;
class GFG
{
/* A linked list node */
public class Node
{
public int data;
public Node next;
};
/* Prints a linked list in reverse manner */
static void fun1(Node head)
{
if (head == null)
{
return;
}
fun1(head.next);
Console.Write(head.data + " ");
}
/* prints alternate nodes of a Linked List, first
from head to end, and then from end to head. */
static void fun2(Node start)
{
if (start == null)
{
return;
}
Console.Write(start.data + " ");
if (start.next != null)
{
fun2(start.next.next);
}
Console.Write(start.data + " ");
}
/* UTILITY FUNCTIONS TO TEST fun1() and fun2() */
/* Given a reference (pointer to pointer) to the head
of a list and an int,.Push a new node on the front
of the list. */
static Node 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 of the new node */
new_node.next = (head_ref);
/* move the head to point to the new node */
(head_ref) = new_node;
return head_ref;
}
/* Driver code */
public static void Main(String[] args)
{
/* Start with the empty list */
Node head = null;
/* Using.Push() to construct below list
1->2->3->4->5 */
head = Push(head, 5);
head = Push(head, 4);
head = Push(head, 3);
head = Push(head, 2);
head = Push(head, 1);
Console.Write("Output of fun1() for " +
"list 1->2->3->4->5 \n");
fun1(head);
Console.Write("\nOutput of fun2() for " +
"list 1->2->3->4->5 \n");
fun2(head);
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript code implementation for above approach
/* A linked list node */
class Node
{
constructor(data) {
this.next = null;
this.data = data;
}
}
/* Prints a linked list in reverse manner */
function fun1(head)
{
if (head == null)
{
return;
}
fun1(head.next);
document.write(head.data + " ");
}
/* prints alternate nodes of a Linked List, first
from head to end, and then from end to head. */
function fun2(start)
{
if (start == null)
{
return;
}
document.write(start.data + " ");
if (start.next != null)
{
fun2(start.next.next);
}
document.write(start.data + " ");
}
/* UTILITY FUNCTIONS TO TEST fun1() and fun2() */
/* Given a reference (pointer to pointer) to the head
of a list and an int,.Push a new node on the front
of the list. */
function Push(head_ref, new_data)
{
/* allocate node */
/* put in the data */
let new_node = new Node(new_data);
/* link the old list of the new node */
new_node.next = (head_ref);
/* move the head to point to the new node */
(head_ref) = new_node;
return head_ref;
}
/* Start with the empty list */
let head = null;
/* Using.Push() to construct below list
1->2->3->4->5 */
head = Push(head, 5);
head = Push(head, 4);
head = Push(head, 3);
head = Push(head, 2);
head = Push(head, 1);
document.write("Output of fun1() for " +
"list 1->2->3->4->5 " + "</br>");
fun1(head);
document.write("</br>");
document.write("Output of fun2() for " +
"list 1->2->3->4->5 " + "</br>");
fun2(head);
// This code is contributed by mukesh07.
</script>
Output:
Output of fun1() for list 1->2->3->4->5
5 4 3 2 1
Output of fun2() for list 1->2->3->4->5
1 3 5 5 3 1
Time complexity: O(n)
Auxiliary Space: O(1)
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above.
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 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