Linked List
Linked List
Linked List
1
Contents
23 Check whether the length of given linked list is Even or Odd 127
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
28 Clone a linked list with next and random pointer in O(1) space 149
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
29 Clone a linked list with next and random pointer | Set 1 154
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
30 Clone a linked list with next and random pointer | Set 2 157
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
2
Contents
32 Construct a Maximum Sum Linked List out of two Sorted Linked Lists
having some Common nodes 170
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
42 Count pairs from two linked lists whose sum is equal to a given value 235
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
43 Count pairs in a binary tree whose sum is equal to a given value x 248
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
3
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
57 Delete all the nodes from the doubly linked list that are greater than a
given value 323
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
58 Delete all the nodes from the list that are greater than x 327
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
62 Delete multiple occurrences of key in Linked list using double pointer 345
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
4
Contents
74 Find a triplet from three linked lists with sum equal to a given number 460
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
77 Find kth node from Middle towards Head of a Linked List 475
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478
5
Contents
81 Find pair for given sum in a sorted singly linked without extra space 489
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
85 Find the fractional (or n/k – th) node in linked list 511
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
88 Find the sum of last n nodes of the given Linked List 526
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
6
Contents
100 Given a linked list which is sorted, how will you insert in sorted way 601
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607
101 Given a linked list, reverse alternate nodes and append at the end 608
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615
105 How does Floyd’s slow and fast pointers approach work? 630
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631
106 How to write C functions that modify head pointer of a Linked List? 632
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635
111 In-place Merge two linked lists without changing links of first list 680
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683
113 Insert a node after the n-th node from the end 693
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 698
7
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 702
115 Insert a whole linked list into other at k-th position 703
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 707
116 Insert node into the middle of the linked list 708
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 717
117 Insert value in sorted way in a sorted doubly linked list 718
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 721
122 Iterative approach for removing middle points in a linked list of line
segements 749
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 752
123 Iteratively Reverse a linked list using only 2 pointers (An Interesting
Method) 753
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 758
127 Length of longest palindrome list in a linked list using O(1) extra space786
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
8
Contents
139 Lucky alive person in a circle | Code Solution to sword puzzle 855
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 857
9
Contents
149 Merge a linked list into another linked list at alternate positions 904
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 910
150 Merge first half and reversed second half of the linked list alternatively911
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 918
151 Merge k sorted linked lists | Set 2 (Using Min Heap) 919
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 922
154 Merge two sorted linked lists such that merged list is in reverse order 935
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 941
159 Move all zeros to the front of the linked list 967
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 970
162 Multiply two numbers represented as linked lists into a third list 979
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 984
10
Contents
166 Pairwise swap elements of a given linked list by changing links 1003
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1011
167 Partitioning a linked list around a given value and If we don’t care
about making the elements of the list “stable” 1012
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1014
168 Partitioning a linked list around a given value and keeping the original
order 1015
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1019
169 Point arbit pointer to greatest value right side node in a linked list 1020
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1025
170 Point to next higher value node in a linked list with an arbitrary pointer 1026
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1031
175 Print reverse of a Linked List without extra space and modifications 1047
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1049
176 Print the alternate nodes of linked list (Iterative Method) 1050
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1053
179 Program for n’th node from the end of a Linked List 1062
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1070
181 Queue based approach for first non-repeating character in a stream 1074
11
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1077
189 Rearrange a linked list in to alternate first and last element 1118
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1120
190 Rearrange a linked list such that all even and odd positioned nodes
are together 1121
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1124
191 Recursive Approach to find nth node from the end in the linked list 1125
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1129
193 Recursive function to delete k-th node from linked list 1133
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1135
195 Recursive selection sort for singly linked list | Swapping node links 1139
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1143
197 Remove all occurrences of duplicates from a sorted Linked List 1147
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1153
12
Contents
200 Remove duplicates from a sorted linked list using recursion 1166
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1168
13
Contents
221 Reverse nodes of a linked list without affecting the special characters 1279
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1285
227 Segregate even and odd nodes in a Linked List using Deque 1327
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1330
14
Contents
236 Sort a linked list that is sorted alternating ascending and descending
orders? 1390
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1399
237 Sort linked list which is already sorted on absolute values 1400
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1405
240 Sort the linked list in the order of elements appearing in the array 1416
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1419
243 Sorted insert in a doubly linked list with head and tail pointers 1437
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1440
244 Sorted merge of two sorted doubly circular linked lists 1441
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1445
15
Contents
252 Swap Kth node from beginning with Kth node from end in a Linked
List 1496
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1502
256 Union and Intersection of two linked lists | Set-2 (Using Merge Sort) 1528
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1534
257 Union and Intersection of two linked lists | Set-3 (Hashing) 1535
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1539
259 Write a function that counts the number of times a given int occurs in
a Linked List 1544
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1551
262 Write a function to get the intersection point of two Linked Lists. 1565
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1572
263 XOR Linked List – A Memory Efficient Doubly Linked List | Set 1 1573
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1574
264 XOR Linked List – A Memory Efficient Doubly Linked List | Set 2 1575
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1578
16
Chapter 1
A Programmer’s approach of
looking at Array vs. Linked List
A linked list with 4 nodes where each node has integer as data and these data are initialized
with 1, 2, 3 and 4. Suppose, these nodes are allocated via malloc() and memory allocated
for them is 0x200, 0x308, 0x404 and 0x20B respectively.
Anyone with even little understanding of array and linked-list might not be interested in the
above explanation. I mean, it is well know that the array elements are allocated memory in
17
Chapter 1. A Programmer’s approach of looking at Array vs. Linked List
sequence i.e. contiguous memory while nodes of a linked list are non-contiguous in memory.
Though it sounds trivial yet this the most important difference between array and linked
list. It should be noted that due to this contiguous versus non-contiguous memory, array
and linked list are different. In fact, this difference is what makes array vs. linked list! In
the following sections, we will try to explore on this very idea further.
Since elements of array are contiguous in memory, we can access any element randomly
using index e.g. intArr[3] will access directly fourth element of the array. (For newbies,
array indexing start from 0 and that’s why fourth element is indexed with 3). Also, due
to contiguous memory for successive elements in array, no extra information is needed to
be stored in individual elements i.e. no overhead of metadata in arrays. Contrary to this,
linked list nodes are non-contiguous in memory. It means that we need some mechanism
to traverse or access linked list nodes. To achieve this, each node stores the location of
next node and this forms the basis of the link from one node to next node. Therefore, it’s
called Linked list. Though storing the location of next node is overhead in linked list but
it’s required. Typically, we see linked list node declaration as follows:
struct llNode
{
int dataInt;
So array elements are contiguous in memory and therefore not requiring any metadata. And
linked list nodes are non-contiguous in memory thereby requiring metadata in the form of
location of next node. Apart from this difference, we can see that array could have several
unused elements because memory has already been allocated. But linked list will have only
the required no. of data items. All the above information about array and linked list has
been mentioned in several textbooks though in different ways.
What if we need to allocate array memory from Heap section (i.e. at run time) and linked
list memory from Data/Stack section. First of all, is it possible? Before that, one might ask
why would someone need to do this? Now, I hope that the remaining article would make
you rethink about the idea of array vs. linked-list �
Now consider the case when we need to store certain data in array (because array has the
property of random access due to contiguous memory) but we don’t know the total size
apriori. One possibility is to allocate memory of this array from Heap at run time. For
example, as follows:
/*At run-time, suppose we know the required size for integer array (e.g. input size from
user). Say, the array size is stored in variable arrSize. Allocate this array from Heap as
follows*/
Though the memory of this array is allocated from Heap, the elements can still be accessed
via index mechanism e.g. dynArr[i]. Basically, based on the programming problem, we have
18
Chapter 1. A Programmer’s approach of looking at Array vs. Linked List
combined one benefit of array (i.e. random access of elements) and one benefit of linked
list (i.e. delaying the memory allocation till run time and allocating memory from Heap).
Another advantage of having this type of dynamic array is that, this method of allocating
array from Heap at run time could reduce code-size (of course, it depends on certain other
factors e.g. program format etc.)
Now consider the case when we need to store data in a linked list (because no. of nodes in
linked list would be equal to actual data items stored i.e. no extra space like array) but we
aren’t allowed to get this memory from Heap again and again for each node. This might look
hypothetical situation to some folks but it’s not very uncommon requirement in embedded
systems. Basically, in several embedded programs, allocating memory via malloc() etc.
isn’t allowed due to multiple reasons. One obvious reason is performance i.e. allocating
memory via malloc() is costly in terms of time complexity because your embedded program
is required to be deterministic most of the times. Another reason could be module specific
memory management i.e. it’s possible that each module in embedded system manages its
own memory. In short, if we need to perform our own memory management, instead of
relying on system provided APIs of malloc() and free(), we might choose the linked list
which is simulated using array. I hope that you got some idea why we might need to
simulate linked list using array. Now, let us first see how this can be done. Suppose, type
of a node in linked list (i.e. underlying array) is declared as follows:
struct sllNode
{
int dataInt;
If we initialize this linked list (which is actually an array), it would look as follows in memory:
The important thing to notice is that all the nodes of the linked list are contiguous in
memory (each one occupying 8 bytes) and nextIndex of each node is set to -1. This (i.e. -1)
is done to denote that the each node of the linked list is empty as of now. This linked list
is denoted by head index 0.
Now, if this linked list is updated with four elements of data part 4, 3, 2 and 1 successively,
it would look as follows in memory. This linked list can be viewed as 0x500 -> 0x508 ->
0x510 -> 0x518.
19
Chapter 1. A Programmer’s approach of looking at Array vs. Linked List
The important thing to notice is nextIndex of last node (i.e. fourth node) is set to -2. This
(i.e. -2) is done to denote the end of linked list. Also, head node of the linked list is index 0.
This concept of simulating linked list using array would look more interesting if we delete
say second node from the above linked list. In that case, the linked list will look as follows
in memory:
The resultant linked list is 0x500 -> 0x510 -> 0x518. Here, it should be noted that even
though we have deleted second node from our linked list, the memory for this node is still
there because underlying array is still there. But the nextIndex of first node now points to
third node (for which index is 2).
Hopefully, the above examples would have given some idea that for the simulated linked list,
we need to write our own API similar to malloc() and free() which would basically be used
to insert and delete a node. Now this is what’s called own memory management. Let us see
how this can be done in algorithmic manner.
There are multiple ways to do so. If we take the simplistic approach of creating linked list
using array, we can use the following logic. For inserting a node, traverse the underlying
array and find a node whose nextIndex is -1. It means that this node is empty. Use this
node as a new node. Update the data part in this new node and set the nextIndex of this
node to current head node (i.e. head index) of the linked list. Finally, make the index of this
new node as head index of the linked list. To visualize it, let us take an example. Suppose
the linked list is as follows where head Index is 0 i.e. linked list is 0x500 -> 0x508 -> 0x518
-> 0x520
After inserting a new node with data 8, the linked list would look as follows with head index
as 2.
So the linked list nodes would be at addresses 0x510 -> 0x500 -> 0x508 -> 0x518 -> 0x520
For deleting a node, we need to set the nextIndex of the node as -1 so that the node is
marked as empty node. But, before doing so, we need to make sure that the nextIndex of
the previous node is updated correctly to index of next node of this node to be deleted. We
20
Chapter 1. A Programmer’s approach of looking at Array vs. Linked List
can see that we have done own memory management for creating a linked list out of the
array memory. But, this is one way of inserting and deleting nodes in this linked list. It can
be easily noticed that finding an empty node is not so efficient in terms of time complexity.
Basically, we’re searching the complete array linearly to find an empty node.
Let us see if we can optimize it further. Basically we can maintain a linked list of empty
nodes as well in the same array. In that case, the linked list would be denoted by two
indexes – one index would be for linked list which has the actual data values i.e. nodes
which have been inserted so far and other index would for linked list of empty nodes. By
doing so, whenever, we need to insert a new node in existing linked list, we can quickly find
an empty node. Let us take an example:
The above linked list which is represented using two indexes (0 and 5) has two linked lists:
one for actual values and another for empty nodes. The linked list with actual values has
nodes at address 0x500 -> 0x510 -> 0x528 while the linked list with empty nodes has nodes
at addresses 0x520 -> 0x508 -> 0x518. It can be seen that finding an empty node (i.e.
writing own API similar to malloc()) should be relatively faster now because we can quickly
find a free node. In real world embedded programs, a fixed chunk of memory (normally
called memory pool) is allocated using malloc() only once by a module. And then the
management of this memory pool (which is basically an array) is done by that module itself
using techniques mentioned earlier. Sometimes, there are multiple memory pools each one
having different size of node. Of course, there are several other aspects of own memory
management but we’ll leave it here itself. But it’s worth mentioning that there are several
methods by which the insertion (which requires our own memory allocation) and deletion
(which requires our own memory freeing) can be improved further.
If we look carefully, it can be noticed that the Heap section of memory is basically a big
array of bytes which is being managed by the underlying operating system (OS). And OS is
providing this memory management service to programmers via malloc(), free() etc. Aha !!
The important take-aways from this article can be summed as follows:
A) Array means contiguous memory. It can exist in any memory section be it Data or Stack
or Heap.
B) Linked List means non-contiguous linked memory. It can exist in any memory section
be it Heap or Data or Stack.
C) As a programmer, looking at a data structure from memory perspective could provide us
better insight in choosing a particular data structure or even designing a new data structure.
For example, we might create an array of linked lists etc.
Source
https://www.geeksforgeeks.org/programmers-approach-looking-array-vs-linked-list/
21
Chapter 2
1. Reverse given linked list. For example, 1-> 9-> 9 -> 9 is converted to 9-> 9 -> 9 ->1.
2. Start traversing linked list from leftmost node and add 1 to it. If there is a carry, move
to the next node. Keep moving to the next node while there is a carry.
3. Reverse modified linked list and return head.
22
Chapter 2. Add 1 to a number represented as linked list
new_node->next = NULL;
return new_node;
}
23
Chapter 2. Add 1 to a number represented as linked list
printf("List is ");
24
Chapter 2. Add 1 to a number represented as linked list
printList(head);
head = addOne(head);
return 0;
}
Output:
List is 1999
Recursive Implementation:
We can recursively reach the last node and forward carry to previous nodes. Recursive
solution doesn’t require reversing of linked list. We can also use a stack in place of recursion
to temporarily hold nodes.
Below is C++ implementation of recursive solution.
25
Chapter 2. Add 1 to a number represented as linked list
// return carry
if (head == NULL)
return 1;
return head;
}
26
Chapter 2. Add 1 to a number represented as linked list
head->next->next->next = newNode(9);
printf("List is ");
printList(head);
head = addOne(head);
return 0;
}
Output:
List is 1999
This article is contributed by Aditya Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/add-1-number-represented-linked-list/
27
Chapter 3
Input:
First List: 5->6->3 // represents number 365
Second List: 8->4->2 // represents number 248
Output
Resultant list: 3->1->6 // represents number 613
Example 2
Input:
First List: 7->5->9->4->6 // represents number 64957
Second List: 8->4 // represents number 48
Output
Resultant list: 5->0->0->5->6 // represents number 65005
Solution
Traverse both lists. One by one pick nodes of both lists and add the values. If sum is more
than 10 then make carry as 1 and reduce sum. If one list has more elements than the other
then consider remaining values of this list as 0. Following is the implementation of this
approach.
C
28
Chapter 3. Add two numbers represented by linked lists | Set 1
#include<stdio.h>
#include<stdlib.h>
/* Adds contents of two linked lists and return the head node of resultant list */
struct Node* addTwoLists (struct Node* first, struct Node* second)
{
struct Node* res = NULL; // res is head node of the resultant list
struct Node *temp, *prev = NULL;
int carry = 0, sum;
29
Chapter 3. Add two numbers represented by linked lists | Set 1
// if this is the first node then set it as head of the resultant list
if(res == NULL)
res = temp;
else // If this is not the first node then connect it to the rest.
prev->next = temp;
if (carry > 0)
temp->next = newNode(carry);
30
Chapter 3. Add two numbers represented by linked lists | Set 1
return 0;
}
Java
class LinkedList {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
/* Adds contents of two linked lists and return the head node of resultant list */
Node addTwoLists(Node first, Node second) {
Node res = null; // res is head node of the resultant list
Node prev = null;
Node temp = null;
int carry = 0, sum;
31
Chapter 3. Add two numbers represented by linked lists | Set 1
if (carry > 0) {
temp.next = new Node(carry);
}
32
Chapter 3. Add two numbers represented by linked lists | Set 1
Python
# Node class
class Node:
33
Chapter 3. Add two numbers represented by linked lists | Set 1
class LinkedList:
34
Chapter 3. Add two numbers represented by linked lists | Set 1
else :
prev.next = temp
if carry > 0:
temp.next = Node(carry)
35
Chapter 3. Add two numbers represented by linked lists | Set 1
Output:
First List is 7 5 9 4 6
Second List is 8 4
Resultant list is 5 0 0 5 6
Time Complexity: O(m + n) where m and n are number of nodes in first and second lists
respectively.
Related Article : Add two numbers represented by linked lists | Set 2
Source
https://www.geeksforgeeks.org/add-two-numbers-represented-by-linked-lists/
36
Chapter 4
Input:
First List: 5->6->3 // represents number 563
Second List: 8->4->2 // represents number 842
Output
Resultant list: 1->4->0->5 // represents number 1405
We have discussed a solution herewhich is for linked lists where least significant digit is first
node of lists and most significant digit is last node. In this problem, most significant node
is first node and least significant digit is last node and we are not allowed to modify the
lists. Recursion is used here to calculate sum from right to left.
Following are the steps.
1) Calculate sizes of given two linked lists.
2) If sizes are same, then calculate sum using recursion. Hold all nodes in recursion call
stack till the rightmost node, calculate sum of rightmost nodes and forward carry to left
side.
3) If size is not same, then follow below steps:
….a) Calculate difference of sizes of two linked lists. Let the difference be diff
….b) Move diff nodes ahead in the bigger linked list. Now use step 2 to calculate sum of
smaller list and right sub-list (of same size) of larger list. Also, store the carry of this sum.
….c) Calculate sum of the carry (calculated in previous step) with the remaining left sub-list
37
Chapter 4. Add two numbers represented by linked lists | Set 2
of larger list. Nodes of this sum are added at the beginning of sum list obtained previous
step.
Following is implementation of the above approach.
C
#include <stdio.h>
#include <stdlib.h>
38
Chapter 4. Add two numbers represented by linked lists | Set 2
// Adds two linked lists of same size represented by head1 and head2 and returns
// head of the resultant linked list. Carry is propagated while returning from
// the recursion
node* addSameSize(Node* head1, Node* head2, int* carry)
{
// Since the function assumes linked lists are of same size,
// check any of the two head pointers
if (head1 == NULL)
return NULL;
int sum;
return result;
}
39
Chapter 4. Add two numbers represented by linked lists | Set 2
// This function is called after the smaller list is added to the bigger
// lists's sublist of same size. Once the right sublist is added, the carry
// must be added toe left side of larger list to get the final result.
void addCarryToRemaining(Node* head1, Node* cur, int* carry, Node** result)
{
int sum;
// The main function that adds two linked lists represented by head1 and head2.
// The sum of two lists is stored in a list referred by result
void addList(Node* head1, Node* head2, Node** result)
{
Node *cur;
int carry = 0;
40
Chapter 4. Add two numbers represented by linked lists | Set 2
else
{
int diff = abs(size1 - size2);
41
Chapter 4. Add two numbers represented by linked lists | Set 2
printList(result);
return 0;
}
Java
42
Chapter 4. Add two numbers represented by linked lists | Set 2
head2 = newnode;
}
else
{
newnode.next = result;
result = newnode;
}
node cur;
43
Chapter 4. Add two numbers represented by linked lists | Set 2
44
Chapter 4. Add two numbers represented by linked lists | Set 2
45
Chapter 4. Add two numbers represented by linked lists | Set 2
list.push(arr2[i], 2);
list.addlists();
list.printlist(list.result);
}
}
Output:
1 0 1 7
Time Complexity: O(m+n) where m and n are the sizes of given two linked lists.
Related Article : Add two numbers represented by linked lists | Set 1
Source
https://www.geeksforgeeks.org/sum-of-two-linked-lists/
46
Chapter 5
Input:
1st number = 5x^2 + 4x^1 + 2x^0
2nd number = 5x^1 + 5x^0
Output:
5x^2 + 9x^1 + 7x^0
Input:
1st number = 5x^3 + 4x^2 + 2x^0
2nd number = 5x^1 + 5x^0
Output:
5x^3 + 4x^2 + 5x^1 + 7x^0
47
Chapter 5. Adding two polynomials using Linked List
48
Chapter 5. Adding two polynomials using Linked List
r->pow = y;
*temp = r;
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
r->next = NULL;
}
else
{
r->coeff = x;
r->pow = y;
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
r->next = NULL;
}
}
49
Chapter 5. Adding two polynomials using Linked List
// Driver program
int main()
{
struct Node *poly1 = NULL, *poly2 = NULL, *poly = NULL;
50
Chapter 5. Adding two polynomials using Linked List
create_node(5,1,&poly2);
create_node(5,0,&poly2);
return 0;
}
Output:
Time Complexity: O(m + n) where m and n are number of nodes in first and second lists
respectively.
Source
https://www.geeksforgeeks.org/adding-two-polynomials-using-linked-list/
51
Chapter 6
Input : 10 -> 1 -> 2 -> 3 -> 5 -> 6 -> 7 -> 8 -> NULL
Output : 1 -> 10 -> 3 -> 2 -> 5 -> 6 -> 7 -> 8 -> NULL
1, 3, 5, 7 occur in odd positons and 10, 2, 6, 8 occur
at even positions in the list
Method 1 (Simple)
In this method, we create two stacks-Odd and Even. We traverse the list and when we
encounter an even node in an odd position we push this node’s address onto Even Stack. If
we encounter an odd node in even position we push this node’s address onto Odd Stack.
After traversing the list, we simply pop the nodes at the top of the two stacks and exchange
their data. We keep repeating this step until the stacks become empty.
Step 1: Create two stacks Odd and Even. These stacks will store the pointers
to the nodes in the list
52
Chapter 6. Alternate Odd and Even Nodes in a Singly Linked List
Step 2: Traverse list from start to end, using the variable current. Repeat
following steps 3-4
Step 3: If current node is even and it occurs at an odd position, push this node’s
address to stack Even
Step 4: If current node is odd and it occurs at an even position, push this node’s
address to stack Odd.
[END OF TRAVERSAL]
Step 5: The size of both the stacks will be same. While both the stacks are
not empty exchange the nodes at the top of the two stacks, and pop both nodes
from their respective stacks.
Step 6: The List is now rearranged. STOP
C++
// Structure node
struct Node {
int data;
struct Node* next;
};
53
Chapter 6. Alternate Odd and Even Nodes in a Singly Linked List
if (head->data % 2 != 0 && i % 2 == 0) {
head = head->next;
i++;
}
// Driver code
54
Chapter 6. Alternate Odd and Even Nodes in a Singly Linked List
int main()
{
Node* head = newNode(8);
head = insertBeg(head, 7);
head = insertBeg(head, 6);
head = insertBeg(head, 5);
head = insertBeg(head, 3);
head = insertBeg(head, 2);
head = insertBeg(head, 1);
return 0;
}
Output:
Linked List:
1 2 3 5 6 7 8
Linked List after Rearranging:
1 2 3 6 5 8 7
1. Segregate odd and even values in the list. After this, all odd values will occur together
followed by all even values.
2. Split the list into two lists odd and even.
3. Merge the even list into odd list
REARRANGE (HEAD)
Step 1: Traverse the list using NODE TEMP.
If TEMP is odd
Add TEMP to the beginning of the List
[END OF IF]
[END OF TRAVERSAL]
Step 2: Set TEMP to 2nd element of LIST.
55
Chapter 6. Alternate Odd and Even Nodes in a Singly Linked List
C++
// Structure node
struct Node {
int data;
struct Node* next;
};
56
Chapter 6. Alternate Odd and Even Nodes in a Singly Linked List
{
Node* temp = new Node;
temp->data = key;
temp->next = NULL;
return temp;
}
57
Chapter 6. Alternate Odd and Even Nodes in a Singly Linked List
temp = x;
}
// Step 2
// Split the List into Odd and even
temp = (*head)->next;
prev_temp = (*head);
even = temp;
// Step 3:
// Merge Even List into odd
i = *head;
j = even;
i->next = j;
j->next = k;
if (i == nullptr) {
58
Chapter 6. Alternate Odd and Even Nodes in a Singly Linked List
// Driver Code
int main()
{
Node* head = newNode(8);
head = insertBeg(head, 7);
head = insertBeg(head, 6);
head = insertBeg(head, 3);
head = insertBeg(head, 5);
head = insertBeg(head, 1);
head = insertBeg(head, 2);
head = insertBeg(head, 10);
Output:
Linked List:
10 2 1 5 3 6 7 8
Rearranged List
7 10 3 2 5 6 1 8
Source
https://www.geeksforgeeks.org/alternate-odd-even-nodes-singly-linked-list/
59
Chapter 7
60
Chapter 7. Alternate sorting of Linked list
};
return newNode;
}
61
Chapter 7. Alternate sorting of Linked list
slow->next = NULL;
}
}
// Base cases
if (a == NULL)
return b;
else if (b == NULL)
return a;
return result;
}
62
Chapter 7. Alternate sorting of Linked list
*head_ref = prev;
}
63
Chapter 7. Alternate sorting of Linked list
head = altSortForLinkedList(head);
return 0;
}
Output:
Original list: 10 9 8 7 6 5
64
Chapter 7. Alternate sorting of Linked list
Modified list: 5 10 6 9 7 8
Source
https://www.geeksforgeeks.org/alternate-sorting-linked-list/
65
Chapter 8
/* pull off the front node of the source and put it in dest */
void MoveNode(struct Node** destRef, struct Node** sourceRef) ;
/* Given the source list, split its nodes into two shorter lists.
If we number the elements 0, 1, 2, ... then all the even elements
66
Chapter 8. Alternating split of a given Singly Linked List | Set 1
should go in the first list, and all the odd elements in the second.
The elements in the new lists may be in any order. */
void AlternatingSplit(struct Node* source, struct Node** aRef,
struct Node** bRef)
{
/* split the nodes of source to these 'a' and 'b' lists */
struct Node* a = NULL;
struct Node* b = NULL;
/* Take the node from the front of the source, and move it to the front of the dest.
It is an error to call this with the source list empty.
67
Chapter 8. Alternating split of a given Singly Linked List | Set 1
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging of the linked list */
void push(struct node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
68
Chapter 8. Alternating split of a given Singly Linked List | Set 1
getchar();
return 0;
}
Time Complexity: O(n) where n is number of node in the given linked list.
Method 2(Using Dummy Nodes)
Here is an alternative approach which builds the sub-lists in the same order as the source list.
The code uses a temporary dummy header nodes for the ‘a’ and ‘b’ lists as they are being
built. Each sublist has a “tail” pointer which points to its current last node — that way
new nodes can be appended to the end of each list easily. The dummy nodes give the tail
pointers something to point to initially. The dummy nodes are efficient in this case because
they are temporary and allocated in the stack. Alternately, local “reference pointers” (which
always points to the last pointer in the list instead of to the last node) could be used to
avoid Dummy nodes.
69
Chapter 8. Alternating split of a given Singly Linked List | Set 1
Time Complexity: O(n) where n is number of node in the given linked list.
Source: http://cslibrary.stanford.edu/105/LinkedListProblems.pdf
Source
https://www.geeksforgeeks.org/alternating-split-of-a-given-singly-linked-list/
70
Chapter 9
Input : list : 85
Output : Reversed Linked list : 85
For printing a list in reverse order, we have already discussed Iterative and Recursive Meth-
ods to Reverse.
In this post, an interesting method is discussed, that doesn’t require recursion and does no
modifications to list. The function also visits every node of linked list only once.
Trick : Idea behind printing a list in reverse order without any recursive function or loop is
to use Carriage return (“r”). For this, we should have knowledge of length of list. Now, we
should print n-1 blanck space and then print 1st element then “r”, futher again n-2 blank
space and 2nd node then “r” and so on..
Carriage return (“r”) : It commands a printer (cursor or the display of a system console),
to move the position of the cursor to the first position on the same line.
71
Chapter 9. An interesting method to print reverse of a linked list
#include <stdio.h>
#include <stdlib.h>
current = current->next;
j++;
}
}
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
72
Chapter 9. An interesting method to print reverse of a linked list
return 0;
}
Output:
73
Chapter 9. An interesting method to print reverse of a linked list
4th Iteration _ _ 3 4 5 6
5th Iteration _ 2 3 4 5 6
Final Output 1 2 3 4 5 6
NOTE:Above program may not work on online compiler because they do not support
anything like carriage return on their console.
Reference :
stackoverflow/Carriage return
Source
https://www.geeksforgeeks.org/an-interesting-method-to-print-reverse-of-a-linked-list/
74
Chapter 10
1. Image viewer – Previous and next images are linked, hence can be accessed by next
and previous button.
75
Chapter 10. Applications of linked list data structure
2. Previous and next page in web browser – We can access previous and next url searched
in web browser by pressing back and next button since, they are linked as linked list.
3. Music Player – Songs in music player are linked to previous and next song. you can
play songs either from starting or ending of the list.
An example problem:
Design a data structure that supports following operations efficiently.
Doubly linked list is the best solution here. We maintain head and tail pointers, since
inserted item is always greatest, we insert at tail. Deleting an item from head or tail can be
done in O(1) time. So all operations take O(1) time.
Recent Articles on Linked List
Source
https://www.geeksforgeeks.org/applications-of-linked-list-data-structure/
76
Chapter 11
Solution :
The idea is to keep a marker of the latest vowel we found while traversing the list. If we
find another vowel, we take it out of the chain and put it after the existing latest vowel.
Example: For linked list:
say our latestVowel reference references the ‘a’ node, and that we currently reached the ‘e’
node. We do:
77
Chapter 11. Arrange consonants and vowels nodes in a linked list
So what was after the ‘a’ node is now after the ‘e’ node after deleting it, and linking ‘a’
directly to ‘e’.
To properly remove and add links, it’s best to use the node before the one you are checking.
So if you have a curr, you will check curr->next node to see if it’s a vowel or not. If it is, we
need to add it after the latestVowel node and then it’s easy to remove it from the chain by
assigning its next to curr’s next. Also if a list only contains consonants, we simply return
head.
78
Chapter 11. Arrange consonants and vowels nodes in a linked list
bool isVowel(char x)
{
return (x == 'a' || x == 'e' || x == 'i' ||
x == 'o' || x == 'u');
}
// list is empty
if (head == NULL)
return NULL;
else
{
79
Chapter 11. Arrange consonants and vowels nodes in a linked list
// Advance latestVowel
latestVowel = latestVowel->next;
80
Chapter 11. Arrange consonants and vowels nodes in a linked list
// Driver code
int main()
{
Node *head = newNode('a');
head->next = newNode('b');
head->next->next = newNode('c');
head->next->next->next = newNode('e');
head->next->next->next->next = newNode('d');
head->next->next->next->next->next = newNode('o');
head->next->next->next->next->next->next = newNode('x');
head->next->next->next->next->next->next->next = newNode('i');
head = arrange(head);
return 0;
}
Output:
81
Chapter 11. Arrange consonants and vowels nodes in a linked list
References:
Stackoverflow
Source
https://www.geeksforgeeks.org/arrange-consonants-vowels-nodes-linked-list/
82
Chapter 12
• Here, start node(set to Head of list), and the last node(set to NULL initially) are
given.
• Middle is calculated using two pointers approach.
• If middle’s data matches the required value of search, return it.
• Else if midele’s data < value, move to upper half(setting last to midele’s next).
• Else go to lower half(setting last to middle).
• The condition to come out is, either element found or entire list is traversed. When
entire list is traversed, last points to start i.e. last -> next == start.
In main function, function InsertAtHead inserts value at the beginning of linked list.
Inserting such values(for sake of simplicity) so that the list created is sorted.
Examples :
83
Chapter 12. Binary Search on Singly Linked List
struct Node
{
int data;
struct Node* next;
};
Node *newNode(int x)
{
struct Node* temp = new Node;
temp->data = x;
temp->next = NULL;
return temp;
}
return slow;
}
84
Chapter 12. Binary Search on Singly Linked List
do
{
// Find middle
Node* mid = middle(start, last);
// If middle is empty
if (mid == NULL)
return NULL;
// Driver Code
int main()
{
Node *head = newNode(1);
head->next = newNode(4);
head->next->next = newNode(7);
head->next->next->next = newNode(8);
head->next->next->next->next = newNode(9);
head->next->next->next->next->next = newNode(10);
int value = 7;
if (binarySearch(head, value) == NULL)
printf("Value not present\n");
else
85
Chapter 12. Binary Search on Singly Linked List
printf("Present");
return 0;
}
Output:
Present
Source
https://www.geeksforgeeks.org/binary-search-on-singly-linked-list/
86
Chapter 13
1. Move fast pointer (or second_pointer) in powers of 2 until we find a loop. After every
power, we reset slow pointer (or first_pointer) to previous value of second pointer.
Reset length to 0 after every every power.
2. The condition for loop testing is first_pointer and second_pointer become same. And
loop is not present if second_pointer becomes NULL.
3. When we come out of loop, we have length of loop.
87
Chapter 13. Brent’s Cycle Detection Algorithm
88
Chapter 13. Brent’s Cycle Detection Algorithm
first_pointer = second_pointer;
}
second_pointer = second_pointer->next;
++length;
}
return first_pointer;
}
89
Chapter 13. Brent’s Cycle Detection Algorithm
{
struct Node* temp =
(struct Node*)malloc(sizeof(struct Node));
temp->data = key;
temp->next = NULL;
return temp;
}
Python3
# Node class
class Node:
# Constructor to initialize
# the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
90
Chapter 13. Brent’s Cycle Detection Algorithm
def __init__(self):
self.head = None
def detectCycle(self):
# if head is null
# then no loop
temp=self.head
if not (temp):
return False
first_p=temp
second_p=temp.next
power = 1
length = 1
91
Chapter 13. Brent’s Cycle Detection Algorithm
length = 0
first_p = second_p
second_p = second_p.next
length=length+1
# if it is null then no loop
if not (second_p) :
return
return first_p
92
Chapter 13. Brent’s Cycle Detection Algorithm
if( res.data):
print ("loop found at ",end=' ')
print (res.data)
else :
print ("No Loop ")
Output:
Loop is present at 15
Time Complexity: O(m + n) where m is the smallest index of the sequence which is the
beginning of a cycle, and n is the cycle’s length.
Auxiliary Space : – O(1) auxiliary
References :
https://en.wikipedia.org/wiki/Cycle_detection#Brent’s_algorithm
github
Source
https://www.geeksforgeeks.org/brents-cycle-detection-algorithm/
93
Chapter 14
Input : 5 4 3 2 1
Output : 1 2 3 4 5
Input : 2 1 3 5 4
Output :1 2 3 4 5
Explanation
As we do in the bubble sort, here also we check elements of two adjacent node whether
they are in ascending order or not, if not then we swap the element. We do this until every
element get its original position.
In 1st pass the largest element get its original position and in 2nd pass 2nd largest element
get its original position and in 3rd pass 3rd largest element get its original position and so
on.
And finally whole list get sorted.
Note: If the list is already sorted then it will do only one pass.
94
Chapter 14. Bubble Sort On Doubly Linked List
// structure of a node
struct Node {
int data;
Node* prev;
Node* next;
};
do
{
swapped = 0;
ptr1 = start;
95
Chapter 14. Bubble Sort On Doubly Linked List
int main()
{
int arr[] = {12, 56, 2, 11, 1, 90};
int list_size, i;
return 0;
}
Output:
96
Chapter 14. Bubble Sort On Doubly Linked List
Source
https://www.geeksforgeeks.org/bubble-sort-on-doubly-linked-list/
97
Chapter 15
Input : 10->30->20->5
Output : 5->10->20->30
Input : 20->4->3
Output : 3->4->20
98
Chapter 15. C Program for Bubble Sort on Linked List
int main()
{
int arr[] = {12, 56, 2, 11, 1, 90};
int list_size, i;
getchar();
return 0;
}
99
Chapter 15. C Program for Bubble Sort on Linked List
while (temp!=NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}
do
{
swapped = 0;
ptr1 = start;
Output:
100
Chapter 15. C Program for Bubble Sort on Linked List
Improved By : YugandharTripathi
Source
https://www.geeksforgeeks.org/c-program-bubble-sort-linked-list/
101
Chapter 16
Input : 56 87 12 49 35
Output :65 78 21 94 53
Algorithm:
The task can be accomplished as:
102
Chapter 16. C Program to reverse each node value in Singly Linked List
int data;
struct Node* next;
};
while (number != 0) {
rem = number % 10;
new_num = new_num * 10 + rem;
number = number / 10;
}
return new_num;
}
if (node == NULL)
return;
node->data = reverse(node->data);
103
Chapter 16. C Program to reverse each node value in Singly Linked List
node = node->next;
}
}
reverseIndividualData(head);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/c-program-reverse-node-value-singly-linked-list/
104
Chapter 17
Source
https://www.geeksforgeeks.org/can-we-reverse-a-linked-list-in-less-than-on/
105
Chapter 18
1. Create a doubly linked list where each node contains only one character of a string.
2. Initialize two pointers left at starting of list and right at the end of the list.
3. Check the data at left node is equal to right node, if it is equal then increment left
and decrement right till middle of the list, if at any stage it is not equal then return
false.
// Structure of node
struct Node
{
char data;
struct Node *next;
struct Node *prev;
106
Chapter 18. Check if a doubly linked list of characters is palindrome or not
};
left = left->next;
right = right->prev;
}
return true;
}
// Driver program
int main()
{
struct Node* head = NULL;
push(&head, 'l');
push(&head, 'e');
push(&head, 'v');
push(&head, 'e');
push(&head, 'l');
107
Chapter 18. Check if a doubly linked list of characters is palindrome or not
if (isPalindrome(head))
printf("It is Palindrome");
else
printf("Not Palindrome");
return 0;
}
Output:
It is Palindrome
Source
https://www.geeksforgeeks.org/check-doubly-linked-list-characters-palindrome-not/
108
Chapter 19
109
Chapter 19. Check if a linked list is Circular Linked List
// Next of head
struct Node *node = head->next;
return 0;
110
Chapter 19. Check if a linked list is Circular Linked List
Output :
No
Yes
Source
https://www.geeksforgeeks.org/check-if-a-linked-list-is-circular-linked-list/
111
Chapter 20
The idea is very simple. Construct a string out of given linked list and check if the con-
structed string is palindrome or not.
C/C++
112
Chapter 20. Check if a linked list of strings forms a palindrome
return true;
}
113
Chapter 20. Check if a linked list of strings forms a palindrome
new_node->next = NULL;
return new_node;
}
isPalindrome(head)? printf("true\n"):
printf("false\n");
return 0;
}
Java
import java.util.Scanner;
Node(String d)
{
data = d;
next = null;
}
}
class LinkedList_Palindrome
{
Node head;
114
Chapter 20. Check if a linked list of strings forms a palindrome
return true;
}
System.out.println(list.isPalindrome());
}
}
// This code has been contributed by Amit Khandelwal
Python
115
Chapter 20. Check if a linked list of strings forms a palindrome
# Node class
class Node:
class LinkedList:
116
Chapter 20. Check if a linked list of strings forms a palindrome
Output:
true
This article is contributed by Aditya Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/check-linked-list-strings-form-palindrome/
117
Chapter 21
Iterative Approach : Traverse the linked list from head to end. For every newly encoun-
tered element, check node -> data > node -> next -> data. If True, do same for each
node else return 0 and Print “No”.
118
Chapter 21. Check if linked list is sorted (Iterative and Recursive)
int data;
struct Node* next;
};
return 0;
}
Output:
Yes
119
Chapter 21. Check if linked list is sorted (Iterative and Recursive)
Recursive Approach :
Check Recursively that node -> data > node -> next -> data, If not, return 0 that
is our terminated condition to come out from recursion else Call Check_List Function
Recursively for next node.
120
Chapter 21. Check if linked list is sorted (Iterative and Recursive)
return 0;
}
Output:
Yes
Source
https://www.geeksforgeeks.org/check-linked-list-sorting-order/
121
Chapter 22
Examples:
122
Chapter 22. Check linked list with a loop is palindrome or not
------- 1
Output: Palindrome
Linked list is 1 2 3 4 1 which is a
not palindrome.
Algorithm:
123
Chapter 22. Check linked list with a loop is palindrome or not
ptr2 = ptr2->next;
124
Chapter 22. Check linked list with a loop is palindrome or not
if (ptr == loop_start)
count = 1;
ptr = ptr->next;
}
125
Chapter 22. Check linked list with a loop is palindrome or not
return 0;
}
Output:
Palindrome
Source
https://www.geeksforgeeks.org/check-linked-list-loop-palindrome-not/
126
Chapter 23
Check whether the length of given linked list is Even or Odd - GeeksforGeeks
Given a linklist, task is to make a function which check whether the length of linklist is even
or odd.
Examples:
Input : 1->2->3->4->NULL
Output : Even
Input : 1->2->3->4->5->NULL
Output : Odd
127
Chapter 23. Check whether the length of given linked list is Even or Odd
// Defining structure
struct Node
{
int data;
struct Node* next;
};
// Push function
void push(struct Node** head, int info)
{
// Allocating node
struct Node* node = (struct Node*) malloc(sizeof(struct Node));
// Driver function
int main(void)
{
struct Node* head = NULL;
128
Chapter 23. Check whether the length of given linked list is Even or Odd
push(&head, 2);
push(&head, 0);
push(&head, 5);
push(&head, 5);
int check = LinkedListLength(head);
Output:
Odd
Source
https://www.geeksforgeeks.org/check-whether-the-length-of-given-linked-list-is-even-or-odd/
129
Chapter 24
130
Chapter 24. Circular Linked List | Set 1 (Introduction and Applications)
4) Circular Doubly Linked Lists are used for implementation of advanced data structures
like Fibonacci Heap.
Next Posts :
Circular Linked List | Set 2 (Traversal)
Circular Singly Linked List | Insertion
Source
https://www.geeksforgeeks.org/circular-linked-list/
131
Chapter 25
In a conventional linked list, we traverse the list from the head node and stop the traversal
when we reach NULL. In a circular linked list, we stop traversal when we reach the first
node again. Following is C code for linked list traversal.
132
Chapter 25. Circular Linked List | Set 2 (Traversal)
}
}
#include<stdio.h>
#include<stdlib.h>
/* If linked list is not NULL then set the next of last node */
if (*head_ref != NULL)
{
while (temp->next != *head_ref)
temp = temp->next;
temp->next = ptr1;
}
else
ptr1->next = ptr1; /*For the first node */
*head_ref = ptr1;
}
133
Chapter 25. Circular Linked List | Set 2 (Traversal)
return 0;
}
Python
class CircularLinkedList:
134
Chapter 25. Circular Linked List | Set 2 (Traversal)
ptr1.next = self.head
else:
ptr1.next = ptr1 # For the first node
self.head = ptr1
Output:
135
Chapter 25. Circular Linked List | Set 2 (Traversal)
Source
https://www.geeksforgeeks.org/circular-linked-list-set-2-traversal/
136
Chapter 26
137
Chapter 26. Circular Queue | Set 2 (Circular Linked List Implementation)
Source
https://www.geeksforgeeks.org/circular-queue-set-2-circular-linked-list-implementation/
138
Chapter 27
In this post, implementation and insertion of a node in a Circular Linked List using singly
linked list are explained.
Implementation
To implement a circular singly linked list, we take an external pointer that points to the
last node of the list. If we have a pointer last pointing to the last node, then last -> next
will point to the first node.
139
Chapter 27. Circular Singly Linked List | Insertion
The ponter last points to node Z and last -> next points to node P.
Why have we taken a pointer that points to the last node instead of first node ?
For insertion of node in the beginning we need traverse the whole list. Also, for insertion
and the end, the whole list has to be traversed. If instead of start pointer we take a pointer
to the last node then in both the cases there won’t be any need to traverse the whole list.
So insertion in the begging or at the end takes constant time irrespective of the length of
the list.
Insertion
A node can be added in three ways:
140
Chapter 27. Circular Singly Linked List | Insertion
After insertion, T is the last node so pointer last points to node T. And Node T is first and
last node, so T is pointing to itself.
Function to insert node in an empty List,
return last;
}
141
Chapter 27. Circular Singly Linked List | Insertion
After insertion,
return last;
}
142
Chapter 27. Circular Singly Linked List | Insertion
After insertion,
143
Chapter 27. Circular Singly Linked List | Insertion
return last;
}
144
Chapter 27. Circular Singly Linked List | Insertion
return last;
}
p = p -> next;
} while (p != last -> next);
cout << item << " not present in the list." << endl;
return last;
}
Following is a complete program that uses all of the above methods to create a circular
singly linked list.
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *next;
};
145
Chapter 27. Circular Singly Linked List | Insertion
return last;
return last;
}
return last;
}
return last;
}
146
Chapter 27. Circular Singly Linked List | Insertion
{
if (last == NULL)
return NULL;
if (p == last)
last = temp;
return last;
}
p = p -> next;
} while(p != last -> next);
cout << item << " not present in the list." << endl;
return last;
147
Chapter 27. Circular Singly Linked List | Insertion
while(p != last->next);
// Driven Program
int main()
{
struct Node *last = NULL;
traverse(last);
return 0;
}
Output:
2 4 6 8 10 12
Source
https://www.geeksforgeeks.org/circular-singly-linked-list-insertion/
148
Chapter 28
Clone a linked list with next and random pointer in O(1) space - GeeksforGeeks
Given a linked list having two pointers in each node. The first one points to the next node
of the list, however the other pointer is random and can point to any node of the list. Write
a program that clones the given list in O(1) space, i.e., without any extra space.
Examples:
Output :
A new linked listidentical to the original list.
In the previous posts Set-1 and Set-2 various methods are discussed, and O(n) space com-
plexity implementation is also available.
In this post we’ll be implementing an algorithm that’d require no additional space as dis-
cussed in Set-1.
Below is the Algorithm:
• Create the copy of node 1 and insert it between node 1 & node 2 in original Linked
List, create the copy of 2 and insert it between 2 & 3.. Continue in this fashion, add
the copy of N afte the Nth node
• Now copy the random link in this fashion
149
Chapter 28. Clone a linked list with next and random pointer in O(1) space
This works because original->next is nothing but copy of original and Original-
>random->next is nothing but copy of random.
• Now restore the original and copy linked lists in this fashion in a single loop.
original->next = original->next->next;
copy->next = copy->next->next;
150
Chapter 28. Clone a linked list with next and random pointer in O(1) space
// Inserting node
curr->next = new Node(curr->data);
curr->next->next = temp;
curr = temp;
}
curr = start;
copy->next = copy->next?copy->next->next:copy->next;
original = original->next;
copy = copy->next;
}
return temp;
}
// Driver code
int main()
{
Node* start = new Node(1);
start->next = new Node(2);
151
Chapter 28. Clone a linked list with next and random pointer in O(1) space
return 0;
}
Output:
Original list :
Data = 1, Random = 3
Data = 2, Random = 1
Data = 3, Random = 5
Data = 4, Random = 5
Data = 5, Random = 2
Cloned list :
Data = 1, Random = 3
Data = 2, Random = 1
Data = 3, Random = 5
Data = 4, Random = 5
Data = 5, Random = 2
152
Chapter 28. Clone a linked list with next and random pointer in O(1) space
Source
https://www.geeksforgeeks.org/clone-linked-list-next-random-pointer-o1-space/
153
Chapter 29
Clone a linked list with next and random pointer | Set 1 - GeeksforGeeks
You are given a Double Link List with one pointer of each node pointing to the next node
just like in a single link list. The second pointer however CAN point to any node in the list
and not just the previous node. Now write a program in O(n) time to duplicate this list.
That is, write a program which will create a copy of this list.
Let us call the second pointer as arbit pointer as it can point to any arbitrary node in the
linked list.
Figure 1
Arbitrary pointers are shown in red and next pointers in black
Method 1 (Uses O(n) extra space)
This method stores the next and arbitrary mappings (of original list) in an array first, then
modifies the original Linked List (to create copy), creates a copy. And finally restores the
original list.
1) Create all nodes in copy linked list using next pointers.
3) Store the node and its next pointer mappings of original linked list.
3) Change next pointer of all nodes in original linked list to point to the corresponding node
154
Chapter 29. Clone a linked list with next and random pointer | Set 1
Figure 2
4) Change the arbit pointer of all nodes in copy linked list to point to corresponding node
in original linked list.
5) Now construct the arbit pointer in copy linked list as below and restore the next pointer
of nodes in the original linked list.
copy_list_node->arbit =
copy_list_node->arbit->arbit->next;
copy_list_node = copy_list_node->next;
6) Restore the next pointers in original linked list from the stored mappings(in step 2).
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 2 (Uses Constant Extra Space)
Thanks to Saravanan Mani for providing this solution. This solution works using constant
space.
1) Create the copy of node 1 and insert it between node 1 & node 2 in original Linked List,
create the copy of 2 and insert it between 2 & 3.. Continue in this fashion, add the copy of
N afte the Nth node
2) Now copy the arbitrary link in this fashion
This works because original->next is nothing but copy of original and Original->arbitrary-
>next is nothing but copy of arbitrary.
3) Now restore the original and copy linked lists in this fashion in a single loop.
155
Chapter 29. Clone a linked list with next and random pointer | Set 1
original->next = original->next->next;
copy->next = copy->next->next;
Source
https://www.geeksforgeeks.org/a-linked-list-with-next-and-arbit-pointer/
156
Chapter 30
Clone a linked list with next and random pointer | Set 2 - GeeksforGeeks
We have already discussed 2 different ways to clone a linked list. In thispost, one more
simple method to clone a linked list is discussed.
The idea is to use Hashing. Below is algorithm.
1. Traverse the original linked list and make a copy in terms of data.
2. Make a hash map of key value pair with original linked list node and copied linked list
node.
3. Traverse the original linked list again and using the hash map adjust the next and random
reference of cloned linked list nodes.
Below is the implementation of above approach.
C++
157
Chapter 30. Clone a linked list with next and random pointer | Set 2
Node(int data)
{
this->data = data;
this->next = this->random = NULL;
}
};
LinkedList(Node *head)
{
this->head = head;
}
158
Chapter 30. Clone a linked list with next and random pointer | Set 2
// list.
LinkedList* clone()
{
// Initialize two references,
// one with original list's head.
Node *origCurr = head;
Node *cloneCurr = NULL;
// driver code
int main()
{
159
Chapter 30. Clone a linked list with next and random pointer | Set 2
mylist->head->next->random =
mylist->head->next->next->next;
mylist->head->next->next->random =
mylist->head->next->next->next->next;
mylist->head->next->next->next->random =
mylist->head->next->next->next->next->next;
mylist->head->next->next->next->next->random =
mylist->head->next;
Java
//Node constructor
160
Chapter 30. Clone a linked list with next and random pointer | Set 2
161
Chapter 30. Clone a linked list with next and random pointer | Set 2
// Driver Class
class Main
{
// Main method.
public static void main(String[] args)
{
// Pushing data in the linked list.
LinkedList list = new LinkedList(new Node(5));
list.push(4);
list.push(3);
list.push(2);
list.push(1);
162
Chapter 30. Clone a linked list with next and random pointer | Set 2
list.head.next.next.next;
list.head.next.next.random =
list.head.next.next.next.next;
list.head.next.next.next.random =
list.head.next.next.next.next.next;
list.head.next.next.next.next.random =
list.head.next;
Output:
Source
https://www.geeksforgeeks.org/clone-linked-list-next-arbit-pointer-set-2/
163
Chapter 31
C++
164
Chapter 31. Compare two strings represented as linked lists
struct Node
{
char c;
struct Node *next;
};
// Driver program
int main()
{
Node *list1 = newNode('g');
list1->next = newNode('e');
list1->next->next = newNode('e');
list1->next->next->next = newNode('k');
list1->next->next->next->next = newNode('s');
list1->next->next->next->next->next = newNode('b');
165
Chapter 31. Compare two strings represented as linked lists
return 0;
}
Java
/* Node Class */
static class Node {
char data;
Node next;
166
Chapter 31. Compare two strings represented as linked lists
int value;
value = list.compare(a, b);
System.out.println(value);
}
}
Python
167
Chapter 31. Compare two strings represented as linked lists
# Driver program
list1 = Node('g')
list1.next = Node('e')
list1.next.next = Node('e')
list1.next.next.next = Node('k')
list1.next.next.next.next = Node('s')
list1.next.next.next.next.next = Node('b')
list2 = Node('g')
list2.next = Node('e')
list2.next.next = Node('e')
list2.next.next.next = Node('k')
list2.next.next.next.next = Node('s')
list2.next.next.next.next.next = Node('a')
Output:
168
Chapter 31. Compare two strings represented as linked lists
Source
https://www.geeksforgeeks.org/compare-two-strings-represented-as-linked-lists/
169
Chapter 32
Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common
nodes - GeeksforGeeks
Given two sorted linked lists, construct a linked list that contains maximum sum path from
start to end. The result list may contain nodes from both input lists. When constructing
the result list, we may switch to the other input list only at the point of intersection (which
mean the two node with the same value in the lists). You are allowed to use O(1) extra
space.
Input:
List1 = 1->3->30->90->120->240->511
List2 = 0->3->12->32->90->125->240->249
Output: Following is maximum sum linked list out of two input lists
list = 1->3->12->32->90->125->240->511
we switch at 3 and 240 to get above maximum sum linked list
We strongly recommend to minimize the browser and try this yourself first.
The idea here in the below solution is to adjust next pointers after common nodes.
1. Start with head of both linked lists and find first common node. Use merging technique
of sorted linked list for that.
2. Keep track of sum of the elements too while doing this and set head of result list based
on greater sum till first common node.
170
Chapter 32. Construct a Maximum Sum Linked List out of two Sorted Linked Lists having
some Common nodes
3. After this till the current pointers of both lists don’t become NULL we need to adjust
the next of prev pointers based on greater sum.
This way it can be done in-place with constant extra space.
Time complexity of the below solution is O(n).
C++
// Method that adjusts the pointers and prints the final list
void finalMaxSumList(Node *a, Node *b)
{
Node *result = NULL;
171
Chapter 32. Construct a Maximum Sum Linked List out of two Sorted Linked Lists having
some Common nodes
{
// Keeping 2 local variables at the start of every
// loop run to keep track of the sum between pre
// and cur pointer elements.
int sum1 = 0, sum2 = 0;
172
Chapter 32. Construct a Maximum Sum Linked List out of two Sorted Linked Lists having
some Common nodes
push(&head2, 130);
push(&head2, 120);
push(&head2, 100);
push(&head2, 90);
push(&head2, 32);
push(&head2, 12);
push(&head2, 3);
173
Chapter 32. Construct a Maximum Sum Linked List out of two Sorted Linked Lists having
some Common nodes
push(&head2, 0);
finalMaxSumList(head1, head2);
return 0;
}
Java
174
Chapter 32. Construct a Maximum Sum Linked List out of two Sorted Linked Lists having
some Common nodes
if (curr1.data<curr2.data)
{
sum1 += curr1.data;
curr1 = curr1.next;
}
else
{
sum2 += curr2.data;
curr2 = curr2.next;
}
}
175
Chapter 32. Construct a Maximum Sum Linked List out of two Sorted Linked Lists having
some Common nodes
llist1.push(120);
176
Chapter 32. Construct a Maximum Sum Linked List out of two Sorted Linked Lists having
some Common nodes
llist1.push(110);
llist1.push(90);
llist1.push(30);
llist1.push(3);
llist1.push(1);
llist2.push(130);
llist2.push(120);
llist2.push(100);
llist2.push(90);
llist2.push(32);
llist2.push(12);
llist2.push(3);
llist2.push(0);
llist1.finalMaxSumList(llist1.head, llist2.head);
}
} /* This code is contributed by Rajat Mishra */
Python
177
Chapter 32. Construct a Maximum Sum Linked List out of two Sorted Linked Lists having
some Common nodes
178
Chapter 32. Construct a Maximum Sum Linked List out of two Sorted Linked Lists having
some Common nodes
# Utility functions
# Inserts a new Node at front of the list.
def push(self, new_data):
# 1 & 2: Allocate the Node &
# Put in the data
new_node = self.Node(new_data)
# 3. Make next of new Node as head
new_node.next = self.head
# 4. Move the head to point to new Node
self.head = new_node
# Driver program
llist1 = LinkedList()
llist2 = LinkedList()
llist1.push(120)
llist1.push(110)
llist1.push(90)
llist1.push(30)
llist1.push(3)
llist1.push(1)
llist2.push(130)
llist2.push(120)
llist2.push(100)
llist2.push(90)
llist2.push(32)
llist2.push(12)
llist2.push(3)
llist2.push(0)
llist1.finalMaxSumList(llist1.head, llist2.head)
Output:
179
Chapter 32. Construct a Maximum Sum Linked List out of two Sorted Linked Lists having
some Common nodes
Exercise
1. Try this problem when auxiliary space is not a constraint.
2. Try this problem when we don’t modify the actual list and create the resultant list.
This article is contributed by Kumar Gautam. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/maximum-sum-linked-list-two-sorted-linked-lists-common-nodes/
180
Chapter 33
Input : 2D matrix
1 2 3
4 5 6
7 8 9
Output :
1 -> 2 -> 3 -> NULL
| | |
v v v
4 -> 5 -> 6 -> NULL
| | |
v v v
7 -> 8 -> 9 -> NULL
| | |
v v v
NULL NULL NULL
C++
181
Chapter 33. Construct a linked list from 2D matrix
182
Chapter 33. Construct a linked list from 2D matrix
}
cout << "\n";
Dp = Dp->down;
}
}
// driver program
int main()
{
// 2D matrix
int arr[][3] = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
int m = 3, n = 3;
Node* head = construct(arr, 0, 0, m, n);
display(head);
return 0;
}
Java
183
Chapter 33. Construct a linked list from 2D matrix
temp.data = arr[i][j];
temp.right = construct(arr, i, j + 1, m, n);
temp.down = construct(arr, i + 1, j, m, n);
return temp;
}
// driver program
public static void main(String args[]) {
// 2D matrix
int arr[][] = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
int m = 3, n = 3;
Node head = construct(arr, 0, 0, m, n);
display(head);
}
}
// This code is contributed by Sumit Ghosh
Output:
184
Chapter 33. Construct a linked list from 2D matrix
1 2 3
4 5 6
7 8 9
Source
https://www.geeksforgeeks.org/construct-linked-list-2d-matrix/
185
Chapter 34
Input: [1 2 3
4 5 6
7 8 9]
Output:
1 -> 2 -> 3 -> NULL
| | |
v v v
4 -> 5 -> 6 -> NULL
| | |
v v v
7 -> 8 -> 9 -> NULL
| | |
v v v
NULL NULL NULL
A recursive solution for this problem has been already discussed in this post. Below is an
iterative approach for the problem:
• The idea is to create m linked lists (m = number of rows) whose each node stores its
right node. The head pointers of each m linked lists are stored in an array of nodes.
186
Chapter 34. Construct a linked list from 2D matrix (Iterative Approach)
• Then, traverse m lists, for every ith and (i+1)th list, set the down pointers of each
node of ith list to its corresponding node of (i+1)th list.
187
Chapter 34. Construct a linked list from 2D matrix (Iterative Approach)
if (!head[i])
head[i] = newptr;
else
188
Chapter 34. Construct a linked list from 2D matrix (Iterative Approach)
righttemp->right = newptr;
righttemp = newptr;
}
}
temp1->down = temp2;
temp1 = temp1->right;
temp2 = temp2->right;
}
}
return 0;
}
Output:
1 2 3
4 5 6
189
Chapter 34. Construct a linked list from 2D matrix (Iterative Approach)
7 8 9
Source
https://www.geeksforgeeks.org/construct-a-linked-list-from-2d-matrix-iterative-approach/
190
Chapter 35
• The left and right pointers in nodes are to be used as previous and next pointers
respectively in converted Circular Linked List.
• The order of nodes in List must be same as Inorder of the given Binary Tree.
• The first node of Inorder traversal must be head node of the Circular List.
Example:
191
Chapter 35. Convert a Binary Tree to a Circular Doubly Link List
192
Chapter 35. Convert a Binary Tree to a Circular Doubly Link List
• Get the last node of the left list. Retrieving the last node is an O(1) operation, since
the prev pointer of the head points to the last node of the list.
• Connect it with the first node of the right list
• Get the last node of the second list
• Connect it with the head of the list.
193
Chapter 35. Convert a Binary Tree to a Circular Doubly Link List
leftList->left = rightLast;
return leftList;
}
194
Chapter 35. Convert a Binary Tree to a Circular Doubly Link List
{
Node *temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
return 0;
}
Java
195
Chapter 35. Convert a Binary Tree to a Circular Doubly Link List
196
Chapter 35. Convert a Binary Tree to a Circular Doubly Link List
// Driver Code
class Main
{
public static void main(String args[])
{
// Build the tree
Tree tree = new Tree();
tree.root = new Node(10);
tree.root.left = new Node(12);
tree.root.right = new Node(15);
tree.root.left.left = new Node(25);
tree.root.left.right = new Node(30);
tree.root.right.left = new Node(36);
197
Chapter 35. Convert a Binary Tree to a Circular Doubly Link List
Output:
Source
https://www.geeksforgeeks.org/convert-a-binary-tree-to-a-circular-doubly-link-list/
198
Chapter 36
I came across this interview during one of my interviews. A similar problem is discussed
in this post. The problem here is simpler as we don’t need to create circular DLL, but a
simple DLL. The idea behind its solution is quite simple and straight.
1. If left subtree exists, process the left subtree
…..1.a) Recursively convert the left subtree to DLL.
…..1.b) Then find inorder predecessor of root in left subtree (inorder predecessor is rightmost
node in left subtree).
199
Chapter 36. Convert a given Binary Tree to Doubly Linked List | Set 1
…..1.c) Make inorder predecessor as previous of root and root as next of inorder predecessor.
2. If right subtree exists, process the right subtree (Below 3 steps are similar to left subtree).
…..2.a) Recursively convert the right subtree to DLL.
…..2.b) Then find inorder successor of root in right subtree (inorder successor is leftmost
node in right subtree).
…..2.c) Make inorder successor as next of root and root as previous of inorder successor.
3. Find the leftmost node and return it (the leftmost node is always head of converted
DLL).
Below is the source code for above algorithm.
C
/* A binary tree node has data, and left and right pointers */
struct node
{
int data;
node* left;
node* right;
};
/* This is the core function to convert Tree to list. This function follows
steps 1 and 2 of the above algorithm */
node* bintree2listUtil(node* root)
{
// Base case
if (root == NULL)
return root;
200
Chapter 36. Convert a given Binary Tree to Doubly Linked List | Set 1
return root;
}
// The main function that first calls bintree2listUtil(), then follows step 3
// of the above algorithm
node* bintree2list(node *root)
{
// Base case
if (root == NULL)
return root;
return (root);
}
201
Chapter 36. Convert a given Binary Tree to Doubly Linked List | Set 1
// Convert to DLL
node *head = bintree2list(root);
return 0;
}
Java
/* A binary tree node has data, and left and right pointers */
class Node
{
int data;
Node left, right;
Node(int item)
{
data = item;
left = right = null;
}
}
202
Chapter 36. Convert a given Binary Tree to Doubly Linked List | Set 1
class BinaryTree
{
Node root;
/* This is the core function to convert Tree to list. This function
follows steps 1 and 2 of the above algorithm */
return node;
203
Chapter 36. Convert a given Binary Tree to Doubly Linked List | Set 1
return node;
}
// Convert to DLL
Node head = tree.bintree2list(tree.root);
204
Chapter 36. Convert a given Binary Tree to Doubly Linked List | Set 1
Python
class Node(object):
def BTToDLLUtil(root):
# Make predecessor as
# previous of root
root.left = left
205
Chapter 36. Convert a given Binary Tree to Doubly Linked List | Set 1
# Make successor as
# next of root
root.right = right
return root
def BTToDLL(root):
if root is None:
return root
return root
def print_list(head):
206
Chapter 36. Convert a given Binary Tree to Doubly Linked List | Set 1
head = head.right
# Driver Code
if __name__ == '__main__':
root = Node(10)
root.left = Node(12)
root.right = Node(15)
root.left.left = Node(25)
root.left.right = Node(30)
root.right.left = Node(36)
head = BTToDLL(root)
print_list(head)
Output:
25 12 30 10 36 15
This article is compiled by Ashish Mangla and reviewed by GeeksforGeeks team. Please
write comments if you find anything incorrect, or you want to share more information about
the topic discussed above.
You may also like to see Convert a given Binary Tree to Doubly Linked List | Set 2 for
another simple and efficient solution.
Improved By : viveksyngh
Source
https://www.geeksforgeeks.org/in-place-convert-a-given-binary-tree-to-doubly-linked-list/
207
Chapter 37
208
Chapter 37. Convert a given Binary Tree to Doubly Linked List | Set 2
2) Fix Right Pointers: The above is intuitive and simple. How to change right pointers
to point to next node in DLL? The idea is to use left pointers fixed in step 1. We start
from the rightmost node in Binary Tree (BT). The rightmost node is the last node in DLL.
Since left pointers are changed to point to previous node in DLL, we can linearly traverse
the complete DLL using these pointers. The traversal would be from last to first node.
While traversing the DLL, we keep track of the previously visited node and change the right
pointer to the previous node. See fixNextPtr() in below implementation.
C
// A tree node
struct node
{
int data;
struct node *left, *right;
};
if (root != NULL)
209
Chapter 37. Convert a given Binary Tree to Doubly Linked List | Set 2
{
fixPrevPtr(root->left);
root->left = pre;
pre = root;
fixPrevPtr(root->right);
}
}
// Start from the rightmost node, traverse back using left pointers.
// While traversing, change right pointer of nodes.
while (root && root->left != NULL)
{
prev = root;
root = root->left;
root->right = prev;
}
// The main function that converts BST to DLL and returns head of DLL
struct node *BTToDLL(struct node *root)
{
// Set the previous pointer
fixPrevPtr(root);
210
Chapter 37. Convert a given Binary Tree to Doubly Linked List | Set 2
printf("\n\n\t\tDLL Traversal\n\n");
printList(head);
return 0;
}
Java
211
Chapter 37. Convert a given Binary Tree to Doubly Linked List | Set 2
fixPrevptr(root.left);
root.left = prev;
prev = root;
fixPrevptr(root.right);
212
Chapter 37. Convert a given Binary Tree to Doubly Linked List | Set 2
{
while (root != null)
{
System.out.print(root.data + " ");
root = root.right;
}
}
System.out.println("\nDLL Traversal");
printlist(head);
}
}
Python
213
Chapter 37. Convert a given Binary Tree to Doubly Linked List | Set 2
prev = None
# Find the right most node in BT or last node in DLL
while(root and root.right != None):
root = root.right
214
Chapter 37. Convert a given Binary Tree to Doubly Linked List | Set 2
def BTToDLL(root):
Output:
25 12 30 10 36 15
DLL Traversal
25 12 30 10 36 15
Time Complexity: O(n) where n is the number of nodes in given Binary Tree. The solution
simply does two traversals of all Binary Tree nodes.
215
Chapter 37. Convert a given Binary Tree to Doubly Linked List | Set 2
This article is contributed by Bala. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/convert-a-given-binary-tree-to-doubly-linked-list-set-2/
216
Chapter 38
Following two different solutions have been discussed for this problem.
Convert a given Binary Tree to Doubly Linked List | Set 1
Convert a given Binary Tree to Doubly Linked List | Set 2
In this post, a third solution is discussed which seems to be the simplest of all. The idea is
to do inorder traversal of the binary tree. While doing inorder traversal, keep track of the
previously visited node in a variable say prev. For every visited node, make it next of prev
and previous of this node as prev.
217
Chapter 38. Convert a given Binary Tree to Doubly Linked List | Set 3
Thanks to rahul, wishall and all other readers for their useful comments on the above two
posts.
Following is C++ implementation of this solution.
C++
/* A binary tree node has data, and left and right pointers */
struct node
{
int data;
node* left;
node* right;
};
218
Chapter 38. Convert a given Binary Tree to Doubly Linked List | Set 3
// Convert to DLL
node *head = NULL;
BinaryTree2DoubleLinkedList(root, &head);
return 0;
}
Java
// A binary tree node has data, left pointers and right pointers
219
Chapter 38. Convert a given Binary Tree to Doubly Linked List | Set 3
class Node
{
int data;
Node left, right;
class BinaryTree
{
Node root;
220
Chapter 38. Convert a given Binary Tree to Doubly Linked List | Set 3
// convert to DLL
tree.BinaryTree2DoubleLinkedList(tree.root);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Output:
25 12 30 10 36 15
Note that use of static variables like above is not a recommended practice (we have used
static for simplicity). Imagine a situation where same function is called for two or more
trees, the old value of prev would be used in next call for a different tree. To avoid such
problems, we can use double pointer or reference to a pointer.
Time Complexity: The above program does a simple inorder traversal, so time complexity
is O(n) where n is the number of nodes in given binary tree.
221
Chapter 38. Convert a given Binary Tree to Doubly Linked List | Set 3
Source
https://www.geeksforgeeks.org/convert-given-binary-tree-doubly-linked-list-set-3/
222
Chapter 39
Below three different solutions have been discussed for this problem.
Convert a given Binary Tree to Doubly Linked List | Set 1
Convert a given Binary Tree to Doubly Linked List | Set 2
Convert a given Binary Tree to Doubly Linked List | Set 3
In the following implementation, we traverse the tree in inorder fashion. We add nodes at
the beginning of current linked list and update head of the list using pointer to head pointer.
Since we insert at the beginning, we need to process leaves in reverse order. For reverse
223
Chapter 39. Convert a given Binary Tree to Doubly Linked List | Set 4
order, we first traverse the right subtree before the left subtree. i.e. do a reverse inorder
traversal.
C++
224
Chapter 39. Convert a given Binary Tree to Doubly Linked List | Set 4
printList(head);
return 0;
}
Java
225
Chapter 39. Convert a given Binary Tree to Doubly Linked List | Set 4
class BinaryTree
{
// 'root' - root of binary tree
Node root;
226
Chapter 39. Convert a given Binary Tree to Doubly Linked List | Set 4
tree.BToDLL(tree.root);
tree.printList(tree.head);
}
}
Output :
227
Chapter 39. Convert a given Binary Tree to Doubly Linked List | Set 4
0 1 2 3 4 5 6 7 8 9
Time Complexity: O(n), as the solution does a single traversal of given Binary Tree.
This article is contributed by Aditya Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/convert-a-given-binary-tree-to-doubly-linked-list-set-4/
228
Chapter 40
The above singly linked list is converted into circular linked list.
Approach: The idea is to traverse the singly linked list and check if the node is the last
node or not. If the node is the last node i.e pointing to NULL then make it point to the
starting node i.e head node. Below is the implementation of this approach.
229
Chapter 40. Convert singly linked list into circular linked list
230
Chapter 40. Convert singly linked list into circular linked list
return 0;
}
Output:
Display list:
17 22 13 14 15
Source
https://www.geeksforgeeks.org/convert-singly-linked-list-circular-linked-list/
231
Chapter 41
We use the concept used inCircular Linked List | Set 2 (Traversal). While traversing, we
keep track of count of nodes.
232
Chapter 41. Count nodes in Circular linked list
ptr1->next = *head_ref;
*head_ref = ptr1;
}
return result;
}
printf("%d", countNodes(head));
return 0;
}
233
Chapter 41. Count nodes in Circular linked list
Source
https://www.geeksforgeeks.org/count-nodes-circular-linked-list/
234
Chapter 42
Count pairs from two linked lists whose sum is equal to a given value - GeeksforGeeks
Given two linked lists(can be sorted or unsorted) of size n1 and n2 of distinct elements.
Given a value x. The problem is to count all pairs from both lists whose sum is equal to
the given value x.
Note: The pair has an element from each linked list.
Examples:
Method 1 (Naive Approach): Using two loops pick elements from both the linked lists
and check whether the sum of the pair is equal to x or not.
C/C++
235
Chapter 42. Count pairs from two linked lists whose sum is equal to a given value
236
Chapter 42. Count pairs from two linked lists whose sum is equal to a given value
if ((p1->data + p2->data) == x)
count++;
int x = 10;
Java
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
class GFG
{
// method to count all pairs from both the linked lists
// whose sum is equal to a given value
237
Chapter 42. Count pairs from two linked lists whose sum is equal to a given value
while(itr2.hasNext())
{
// if sum of pair is equal to 'x'
// increment count
if ((itr1.next() + itr2.next()) == x)
count++;
}
}
// Driver method
public static void main(String[] args)
{
Integer arr1[] = {3, 1, 5, 7};
Integer arr2[] = {8, 2, 5, 3};
int x = 10;
Output:
Count = 2
238
Chapter 42. Count pairs from two linked lists whose sum is equal to a given value
Method 2 (Sorting): Sort the 1st linked list in ascending order and the 2nd linked list in
descending order using merge sort technique. Now traverse both the lists from left to right
in the following way:
Algorithm:
countPairs(list1, list2, x)
Initialize count = 0
while list != NULL and list2 != NULL
if (list1->data + list2->data) == x
list1 = list1->next
list2 = list2->next
count++
else if (list1->data + list2->data) > x
list2 = list2->next
else
list1 = list1->next
return count
For simplicity, the implementation given below assumes that list1 is sorted in ascending
order and list2 is sorted in descending order.
C/C++
239
Chapter 42. Count pairs from two linked lists whose sum is equal to a given value
240
Chapter 42. Count pairs from two linked lists whose sum is equal to a given value
return count;
}
int x = 10;
Java
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
class GFG
{
// method to count all pairs from both the linked lists
// whose sum is equal to a given value
static int countPairs(LinkedList<Integer> head1, LinkedList<Integer> head2, int x)
241
Chapter 42. Count pairs from two linked lists whose sum is equal to a given value
{
int count = 0;
if ((num1 + num2) == x)
{
num1 = itr1.hasNext() ? itr1.next() : null;
num2 = itr2.hasNext() ? itr2.next() : null;
count++;
}
// Driver method
public static void main(String[] args)
{
Integer arr1[] = {3, 1, 5, 7};
242
Chapter 42. Count pairs from two linked lists whose sum is equal to a given value
int x = 10;
Output:
Count = 2
243
Chapter 42. Count pairs from two linked lists whose sum is equal to a given value
unordered_set<int> us;
244
Chapter 42. Count pairs from two linked lists whose sum is equal to a given value
{
struct Node* head1 = NULL;
struct Node* head2 = NULL;
int x = 10;
Java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
class GFG
{
// method to count all pairs from both the linked lists
// whose sum is equal to a given value
static int countPairs(LinkedList<Integer> head1, LinkedList<Integer> head2, int x)
{
int count = 0;
245
Chapter 42. Count pairs from two linked lists whose sum is equal to a given value
// Driver method
public static void main(String[] args)
{
Integer arr1[] = {3, 1, 5, 7};
Integer arr2[] = {8, 2, 5, 3};
int x = 10;
Output:
Count = 2
246
Chapter 42. Count pairs from two linked lists whose sum is equal to a given value
Source
https://www.geeksforgeeks.org/count-pairs-two-linked-lists-whose-sum-equal-given-value/
247
Chapter 43
Count pairs in a binary tree whose sum is equal to a given value x - GeeksforGeeks
Given a binary tree containing n distinct numbers and a value x. The problem is to count
pairs in the given binary tree whose sum is equal to the given value x.
Examples:
Input :
5
/ \
3 7
/ \ / \
2 4 6 8
x = 10
Output : 3
The pairs are (3, 7), (2, 8) and (4, 6).
Naive Approach: One by one get each node of the binary tree through any of the tree
traversals method. Pass the node say temp, the root of the tree and value x to another
function say findPair(). In the function with the help of the root pointer traverse the tree
again. One by one sum up these nodes with temp and check whether sum == x. If so,
increment count. Calculate count = count / 2 as a single pair has been counted twice by
the aforementioned method.
248
Chapter 43. Count pairs in a binary tree whose sum is equal to a given value x
// pair exists
if (root != temp && ((root->data + temp->data) == x))
return true;
249
Chapter 43. Count pairs in a binary tree whose sum is equal to a given value x
int x = 10;
int count = 0;
return 0;
}
Output:
Count = 3
1. Convert given binary tree to doubly linked list. Refer this post.
2. Sort the doubly linked list obtained in Step 1. Refer this post.
3. Count Pairs in sorted doubly linked with sum equal to ‘x’. Refer this post.
250
Chapter 43. Count pairs in a binary tree whose sum is equal to a given value x
251
Chapter 43. Count pairs in a binary tree whose sum is equal to a given value x
252
Chapter 43. Count pairs in a binary tree whose sum is equal to a given value x
if (!head || !head->right)
return head;
Node* second = split(head);
int count = 0;
return count;
253
Chapter 43. Count pairs in a binary tree whose sum is equal to a given value x
// sort DLL
head = mergeSort(head);
// count pairs
return pairSum(head, x);
}
int x = 10;
return 0;
}
Output:
Count = 3
254
Chapter 43. Count pairs in a binary tree whose sum is equal to a given value x
Source
https://www.geeksforgeeks.org/count-pairs-in-a-binary-tree-whose-sum-is-equal-to-a-given-value-x/
255
Chapter 44
The idea is to traverse singly linked list to check condition whether current node value
is greater than value of next node. If the given condition is true, then break the loop.
Otherwise increase the counter variable and increase the node by node->next. Below is the
implementation of this approach.
256
Chapter 44. Count rotations in sorted and rotated linked list
count++;
257
Chapter 44. Count rotations in sorted and rotated linked list
{
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
// Drier functions
int main()
{
// Create a node and initialize with NULL
struct Node* head = NULL;
printList(head);
cout << endl;
cout << "Linked list rotated elements: ";
return 0;
}
Output:
Linked List:
15 18 5 8 11 12
Linked list rotated elements: 2
Source
https://www.geeksforgeeks.org/count-rotations-sorted-rotated-linked-list/
258
Chapter 45
Count triplets in a sorted doubly linked list whose sum is equal to a given value x - Geeks-
forGeeks
Given a sorted doubly linked list of distinct nodes(no two nodes have the same data) and a
value x. Count triplets in the list that sum up to a given value x.
Examples:
259
Chapter 45. Count triplets in a sorted doubly linked list whose sum is equal to a given
value x
// increment count
count++;
if ((*head) == NULL)
(*head) = temp;
else {
temp->next = *head;
(*head)->prev = temp;
(*head) = temp;
}
}
260
Chapter 45. Count triplets in a sorted doubly linked list whose sum is equal to a given
value x
int x = 17;
Output:
Count = 2
261
Chapter 45. Count triplets in a sorted doubly linked list whose sum is equal to a given
value x
int data;
struct Node* next, *prev;
};
// increment count
count++;
}
262
Chapter 45. Count triplets in a sorted doubly linked list whose sum is equal to a given
value x
if ((*head) == NULL)
(*head) = temp;
else {
temp->next = *head;
(*head)->prev = temp;
(*head) = temp;
}
}
int x = 17;
Output:
Count = 2
263
Chapter 45. Count triplets in a sorted doubly linked list whose sum is equal to a given
value x
// pair found
if ((first->data + second->data) == value) {
// increment count
count++;
264
Chapter 45. Count triplets in a sorted doubly linked list whose sum is equal to a given
value x
if ((*head) == NULL)
(*head) = temp;
else {
265
Chapter 45. Count triplets in a sorted doubly linked list whose sum is equal to a given
value x
temp->next = *head;
(*head)->prev = temp;
(*head) = temp;
}
}
int x = 17;
Output:
Count = 2
Source
https://www.geeksforgeeks.org/count-triplets-sorted-doubly-linked-list-whose-sum-equal-given-value-x/
266
Chapter 46
1. Left pointer of ternary tree should act as prev pointer of doubly linked list.
2. Middle pointer of ternary tree should not point to anything.
3. Right pointer of ternary tree should act as next pointer of doubly linked list.
4. Each node of ternary tree is inserted into doubly linked list before its subtrees and for
any node, its left child will be inserted first, followed by mid and right child (if any).
For the above example, the linked list formed for below tree should be NULL 5 1 4 8 11 6
7 15 63 31 55 65 -> NULL
267
Chapter 46. Create a Doubly Linked List from a Ternary Tree
We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to traverse the tree in preoder fashion similar to binary tree preorder traversal.
Here, when we visit a node, we will insert it into doubly linked list in the end using a tail
pointer. That we use to maintain the required insertion order. We then recursively call for
left child, middle child and right child in that order.
Below is the implementation of this idea.
C++
/* A ternary tree */
struct Node
{
int data;
struct Node *left, *middle, *right;
};
268
Chapter 46. Create a Doubly Linked List from a Ternary Tree
node->data = data;
node->left = node->middle = node->right = NULL;
return node;
}
return;
}
269
Chapter 46. Create a Doubly Linked List from a Ternary Tree
root->left = newNode(5);
root->middle = newNode(11);
root->right = newNode(63);
root->left->left = newNode(1);
root->left->middle = newNode(4);
root->left->right = newNode(8);
root->middle->left = newNode(6);
root->middle->middle = newNode(7);
root->middle->right = newNode(15);
root->right->left = newNode(31);
270
Chapter 46. Create a Doubly Linked List from a Ternary Tree
root->right->middle = newNode(55);
root->right->right = newNode(65);
TernaryTreeToList(root, &head);
printList(head);
return 0;
}
Java
class GFG {
271
Chapter 46. Create a Doubly Linked List from a Ternary Tree
272
Chapter 46. Create a Doubly Linked List from a Ternary Tree
Output:
Improved By : MvssTeja
Source
https://www.geeksforgeeks.org/create-doubly-linked-list-ternary-ree/
273
Chapter 47
1. add() in O(n)
2. getMinimum() in O(1)
3. deleteMinimum() in O(1)
// Node class
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
274
Chapter 47. Data Structure design to perform required operations
// main class
class MinDS
{
Node start;
public MinDS()
{
start = null;
}
275
Chapter 47. Data Structure design to perform required operations
}
prev.next = tmp;
}
// Driver code
public static void main(String[] args)
{
MinDS x = new MinDS();
x.addElement(10);
x.addElement(20);
x.addElement(5);
x.addElement(15);
x.print();
276
Chapter 47. Data Structure design to perform required operations
Output:
Get Min: 5
Del Min: 5
Elements: 10, 15, 20,
Min: 10
Source
https://www.geeksforgeeks.org/data-structure-design-perform-required-operations/
277
Chapter 48
Input : 0->0->0->1->1->0->0->1->0
Output : 50
Input : 1->0->0
Output : 4
278
Chapter 48. Decimal Equivalent of Binary Linked List
{
// Initialized result
int res = 0;
// Move next
head = head->next;
}
return res;
}
return 0;
}
Output :
Decimal value is 11
Source
https://www.geeksforgeeks.org/decimal-equivalent-of-binary-linked-list/
279
Chapter 49
Input:
M = 2, N = 2
Linked List: 1->2->3->4->5->6->7->8
Output:
Linked List: 1->2->5->6
Input:
M = 3, N = 2
Linked List: 1->2->3->4->5->6->7->8->9->10
Output:
Linked List: 1->2->3->6->7->8
Input:
M = 1, N = 1
Linked List: 1->2->3->4->5->6->7->8->9->10
Output:
Linked List: 1->3->5->7->9
The main part of the problem is to maintain proper links between nodes, make sure that all
corner cases are handled. Following is C implementation of function skipMdeleteN() that
skips M nodes and delete N nodes till end of list. It is assumed that M cannot be 0.
280
Chapter 49. Delete N nodes after M nodes of a linked list
// Function to skip M nodes and then delete N nodes of the linked list.
void skipMdeleteN(struct Node *head, int M, int N)
{
struct Node *curr = head, *t;
int count;
281
Chapter 49. Delete N nodes after M nodes of a linked list
while (curr)
{
// Skip M nodes
for (count = 1; count<M && curr!= NULL; count++)
curr = curr->next;
skipMdeleteN(head, M, N);
282
Chapter 49. Delete N nodes after M nodes of a linked list
return 0;
}
Python
# Node class
class Node:
class LinkedList:
283
Chapter 49. Delete N nodes after M nodes of a linked list
if curr is None :
return
llist.skipMdeleteN(M, N)
Output:
M = 2, N = 3
284
Chapter 49. Delete N nodes after M nodes of a linked list
This article is contributed by Chandra Prakash. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/delete-n-nodes-after-m-nodes-of-a-linked-list/
285
Chapter 50
1. Get the pointer to the node at position n by traversing the doubly linked list up to
the nth node from the beginning.
2. Delete the node using the pointer obtained in Step 1. Refer this post.
286
Chapter 50. Delete a Doubly Linked List node at a given position
287
Chapter 50. Delete a Doubly Linked List node at a given position
current = current->next;
288
Chapter 50. Delete a Doubly Linked List node at a given position
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
int n = 2;
return 0;
}
Output:
Time Complexity: O(n), in worst case where n is the number of nodes in the doubly linked
list.
Source
https://www.geeksforgeeks.org/delete-doubly-linked-list-node-given-position/
289
Chapter 51
If node to be deleted is root, simply delete it. To delete a middle node, we must have pointer
to the node previous to the node to be deleted. So if positions is not zero, we run a loop
position-1 times and get pointer to the previous node.
Below is the implementation of above idea.
C/C++
290
Chapter 51. Delete a Linked List node at a given position
};
291
Chapter 51. Delete a Linked List node at a given position
push(&head, 7);
push(&head, 1);
push(&head, 3);
push(&head, 2);
push(&head, 8);
Java
292
Chapter 51. Delete a Linked List node at a given position
next = null;
}
}
293
Chapter 51. Delete a Linked List node at a given position
llist.push(7);
llist.push(1);
llist.push(3);
llist.push(2);
llist.push(8);
Python
# Node class
class Node:
294
Chapter 51. Delete a Linked List node at a given position
class LinkedList:
295
Chapter 51. Delete a Linked List node at a given position
temp.next = next
Output:
Thanks to Hemanth Kumar for suggesting initial solution. Please write comments if you
find anything incorrect, or you want to share more information about the topic discussed
above
Source
https://www.geeksforgeeks.org/delete-a-linked-list-node-at-a-given-position/
296
Chapter 52
#include <stdio.h>
#include <stdlib.h>
297
Chapter 52. Delete a given node in Linked List under given constraints
};
// free memory
free(n);
return;
}
// Free memory
free(n);
298
Chapter 52. Delete a given node in Linked List under given constraints
return;
}
299
Chapter 52. Delete a given node in Linked List under given constraints
getchar();
return 0;
}
Java
// Java program to delete a given node in linked list under given constraints
class LinkedList {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
300
Chapter 52. Delete a given node in Linked List under given constraints
// free memory
System.gc();
return;
}
// Free memory
System.gc();
return;
}
301
Chapter 52. Delete a given node in Linked List under given constraints
}
}
Output:
Source
https://www.geeksforgeeks.org/delete-a-given-node-in-linked-list-under-given-constraints/
302
Chapter 53
303
Chapter 53. Delete a linked list using recursion
Output:
Source
https://www.geeksforgeeks.org/delete-linked-list-using-recursion/
304
Chapter 54
305
Chapter 54. Delete a node in a Doubly Linked List
Algorithm
Let the node to be deleted is del.
1) If node to be deleted is head node, then change the head pointer to next current head.
2) Set next of previous to del, if previous to del exists.
3) Set prev of next to del, if next to del exists.
C
#include <stdio.h>
#include <stdlib.h>
306
Chapter 54. Delete a node in a Doubly Linked List
{
int data;
struct Node *next;
struct Node *prev;
};
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginning of the Doubly Linked List */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
307
Chapter 54. Delete a node in a Doubly Linked List
new_node->next = (*head_ref);
getchar();
}
308
Chapter 54. Delete a node in a Doubly Linked List
Java
class LinkedList {
class Node {
int data;
Node next, prev;
Node(int d) {
data = d;
next = prev = null;
}
}
/* base case */
if (head == null || del == null) {
return;
}
309
Chapter 54. Delete a node in a Doubly Linked List
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginning of the Doubly Linked List */
void push(Node head_ref, int new_data) {
/* allocate node */
Node new_node = new Node(new_data);
310
Chapter 54. Delete a node in a Doubly Linked List
Python
class DoublyLinkedList:
# Constructor for empty Doubly Linked List
def __init__(self):
self.head = None
# Base Case
if self.head is None or dele is None:
return
311
Chapter 54. Delete a node in a Doubly Linked List
# 1. Allocates node
# 2. Put the data in it
new_node = Node(new_data)
312
Chapter 54. Delete a node in a Doubly Linked List
dll.push(10);
Source
https://www.geeksforgeeks.org/delete-a-node-in-a-doubly-linked-list/
313
Chapter 55
Algorithm:
delAllOccurOfGivenKey(head_ref, x)
if head_ref == NULL
return
Initialize current = head_ref
Declare next
while current != NULL
if current->data == x
next = current->next
deleteNode(head_ref, current)
current = next
else
current = current->next
The algorithm for deleteNode(head_ref, current) (which deletes the node using the
pointer to the node) is discussed in this post.
314
Chapter 55. Delete all occurrences of a given key in a doubly linked list
315
Chapter 55. Delete all occurrences of a given key in a doubly linked list
/* update current */
current = next;
}
316
Chapter 55. Delete all occurrences of a given key in a doubly linked list
int x = 2;
317
Chapter 55. Delete all occurrences of a given key in a doubly linked list
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/delete-occurrences-given-key-doubly-linked-list/
318
Chapter 56
This is mainly an extension of this post which deletes first occurrence of a given key.
We need to first check for all occurrences at head node and change the head node appropri-
ately. Then we need to check for all occurrences inside a loop and delete them one by one.
Following is C implementation for the same.
319
Chapter 56. Delete all occurrences of a given key in a linked list
320
Chapter 56. Delete all occurrences of a given key in a linked list
push(&head, 7);
push(&head, 2);
push(&head, 3);
push(&head, 2);
push(&head, 8);
push(&head, 1);
push(&head, 2);
push(&head, 2);
deleteKey(&head, key);
puts("\nLinked List after Deletion of 1: ");
printList(head);
return 0;
}
Output:
This article is contributed by Saransh. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above.
321
Chapter 56. Delete all occurrences of a given key in a linked list
Source
https://www.geeksforgeeks.org/delete-occurrences-given-key-linked-list/
322
Chapter 57
Delete all the nodes from the doubly linked list that are greater than a given value - Geeks-
forGeeks
Given a doubly linked list containing N nodes and a number X, the task is to delete all the
nodes from the list that are greater than the given value X.
Examples:
Approach: Traverse the nodes of the doubly linked list one by one and get the pointer of
the nodes having data value greater than x. Delete these nodes by following the approach
used in this post.
323
Chapter 57. Delete all the nodes from the doubly linked list that are greater than a given
value
int data;
Node *prev, *next;
};
324
Chapter 57. Delete all the nodes from the doubly linked list that are greater than a given
value
return;
}
325
Chapter 57. Delete all the nodes from the doubly linked list that are greater than a given
value
push(&head, 4);
push(&head, 8);
push(&head, 10);
int x = 9;
deleteGreaterNodes(&head, x);
Output:
Original List: 10 8 4 11 9
Modified List: 8 4 9
Source
https://www.geeksforgeeks.org/delete-all-the-nodes-from-the-doubly-linked-list-that-are-greater-than-a-given-value
326
Chapter 58
Delete all the nodes from the list that are greater than x - GeeksforGeeks
Given a linked list, the problem is to delete all the nodes from the list that are greater than
the specified value x.
Examples:
327
Chapter 58. Delete all the nodes from the list that are greater than x
// structure of a node
struct Node {
int data;
Node* next;
};
328
Chapter 58. Delete all the nodes from the list that are greater than x
int x = 6;
deleteGreaterNodes(&head, x);
return 0;
}
Output:
Original List: 7 3 4 8 5 1
Modified List: 3 4 5 1
329
Chapter 58. Delete all the nodes from the list that are greater than x
Source
https://www.geeksforgeeks.org/delete-nodes-list-greater-x/
330
Chapter 59
331
Chapter 59. Delete alternate nodes of a Linked List
/* Free memory */
free(node);
332
Chapter 59. Delete alternate nodes of a Linked List
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
deleteAlt(head);
return 0;
}
Java
void deleteAlt()
{
if (head == null)
return;
333
Chapter 59. Delete alternate nodes of a Linked List
{
/* Change next link of previus node */
prev.next = now.next;
/* Free node */
now = null;
/* Utility functions */
334
Chapter 59. Delete alternate nodes of a Linked List
llist.deleteAlt();
Output:
Time Complexity: O(n) where n is the number of nodes in the given Linked List.
Method 2 (Recursive)
Recursive code uses the same approach as method 1. The recursive coed is simple and short,
but causes O(n) recursive function calls for a linked list of size n.
if (node == NULL)
return;
335
Chapter 59. Delete alternate nodes of a Linked List
Source
https://www.geeksforgeeks.org/delete-alternate-nodes-of-a-linked-list/
336
Chapter 60
The idea is to traverse the linked list from beginning to end. While traversing, keep track
of last occurrence key. After traversing the complete list, delete last occurrence by copying
data of next node and deleting the next node.
337
Chapter 60. Delete last occurrence of an item from linked list
// deleted
Node* temp = head;
while (temp) {
// If we found the key, update xv
if (temp->key == key)
x = temp;
temp = temp->next;
}
338
Chapter 60. Delete last occurrence of an item from linked list
Output:
The above solution doesn’t work when the node to be deleted is the last node.
Following solution handles all cases.
339
Chapter 60. Delete last occurrence of an item from linked list
340
Chapter 60. Delete last occurrence of an item from linked list
Output:
Source
https://www.geeksforgeeks.org/delete-last-occurrence-of-an-item-from-linked-list/
341
Chapter 61
342
Chapter 61. Delete middle of linked list
return head;
}
343
Chapter 61. Delete middle of linked list
{
struct Node *temp = new Node;
temp->data = data;
temp->next = NULL;
return temp;
}
head = deleteMid(head);
return 0;
}
Output :
Source
https://www.geeksforgeeks.org/delete-middle-of-linked-list/
344
Chapter 62
Delete multiple occurrences of key in Linked list using double pointer - GeeksforGeeks
Given a singly linked list, delete all occurrences of a given key in it. For example, consider
the following list.
This is mainly an alternative of this post which deletes multiple occurrences of a given
key using separate condition loops for head and remaining nodes. Here we use a double
pointer approach to use a single loop irrespective of the position of the element (head, tail
or between). The original method to delete a node from a linked list without an extra check
for the head was explained by Linus Torvalds in his “25th Anniversary of Linux” TED talk.
This article uses that logic to delete multiple recurrences of the key without an extra check
for the head.
Explanation:
1. Store address of head in a double pointer till we find a non “key” node. This takes care
of the 1st while loop to handle the special case of the head.
2. If a node is not “key” node then store the address of node->next in pp.
3. if we find a “key” node later on then change pp (ultimately node->next) to point to
current node->next.
Following is C++ implementation for the same.
345
Chapter 62. Delete multiple occurrences of key in Linked list using double pointer
346
Chapter 62. Delete multiple occurrences of key in Linked list using double pointer
}
}
int main()
{
push(2);
push(2);
push(4);
push(3);
push(2);
Output:
Source
https://www.geeksforgeeks.org/delete-multiple-occurrences-of-key-in-linked-list-using-double-pointer/
347
Chapter 63
348
Chapter 63. Delete nodes which have a greater value on right side
/* Initialize max */
struct Node* maxnode = head;
struct Node* temp;
349
Chapter 63. Delete nodes which have a greater value on right side
350
Chapter 63. Delete nodes which have a greater value on right side
delLesserNodes(&head);
return 0;
}
Java
351
Chapter 63. Delete nodes which have a greater value on right side
/* Initialise max */
Node maxnode = head;
Node temp;
/* Utility functions */
352
Chapter 63. Delete nodes which have a greater value on right side
353
Chapter 63. Delete nodes which have a greater value on right side
llist.push(6);
llist.push(5);
llist.push(11);
llist.push(10);
llist.push(15);
llist.push(12);
llist.delLesserNodes();
Output:
Source:
https://www.geeksforgeeks.org/forum/topic/amazon-interview-question-for-software-engineerdeveloper-about-linke
Source
https://www.geeksforgeeks.org/delete-nodes-which-have-a-greater-value-on-right-side/
354
Chapter 64
We will be given a node and our task is to delete that node from the circular linked list.
Examples:
Algorithm
355
Chapter 64. Deletion from a Circular Linked List
• If the list is not empty then we define two pointers curr and prev and initialize the
pointer curr with the head node.
• Traverse the list using curr to find the node to be deleted and before moving curr to
next node, everytime set prev = curr.
• If the node is found, check if it is the only node in the list. If yes, set head = NULL
and free(curr).
• If the list has more than one node, check if it is the first node of the list. Condition
to check this( curr == head). If yes, then move prev until it reaches the last node.
After prev reaches the last node, set head = head -> next and prev -> next = head.
Delete curr.
• If curr is not first node, we check if it is the last node in the list. Condition to check
this is (curr -> next == head).
• If curr is the last node. Set prev -> next = head and delete the node curr by free(curr).
• If the node to be deleted is neither the first node nor the last node, then set prev ->
next = temp -> next and delete curr.
356
Chapter 64. Deletion from a Circular Linked List
*head_ref = ptr1;
}
printf("\n");
}
357
Chapter 64. Deletion from a Circular Linked List
prev = curr;
curr = curr -> next;
}
358
Chapter 64. Deletion from a Circular Linked List
push(&head, 2);
push(&head, 5);
push(&head, 7);
push(&head, 8);
push(&head, 10);
deleteNode(head, 7);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/deletion-circular-linked-list/
359
Chapter 65
We also recommend to read following post as a prerequisite of the solution discussed here.
360
Chapter 65. Detect and Remove Loop in a Linked List
to remove cycle. There are following two different ways of removing loop when Floyd’s
algorithm is used for Loop detection.
Method 1 (Check one by one)
We know that Floyd’s Cycle detection algorithm terminates when fast and slow pointers
meet at a common point. We also know that this common point is one of the loop nodes
(2 or 3 or 4 or 5 in the above diagram). We store the address of this in a pointer variable
say ptr2. Then we start from the head of the Linked List and check for nodes one by one
if they are reachable from ptr2. When we find a node that is reachable, we know that this
node is the starting node of the loop in Linked List and we can get pointer to the previous
of this node.
C
#include<stdio.h>
#include<stdlib.h>
361
Chapter 65. Detect and Remove Loop in a Linked List
/* If ptr2 did't reach ptr1 then try the next node after ptr1 */
ptr1 = ptr1->next;
}
/* After the end of loop ptr2 is the last node of the loop. So
make next of ptr2 as NULL */
ptr2->next = NULL;
}
362
Chapter 65. Detect and Remove Loop in a Linked List
detectAndRemoveLoop(head);
Java
class LinkedList {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
363
Chapter 65. Detect and Remove Loop in a Linked List
/* If ptr2 did't reach ptr1 then try the next node after ptr1 */
ptr1 = ptr1.next;
}
/* After the end of loop ptr2 is the last node of the loop. So
make next of ptr2 as NULL */
ptr2.next = null;
}
364
Chapter 65. Detect and Remove Loop in a Linked List
Python
# Node class
class Node:
class LinkedList:
def detectAndRemoveLoop(self):
slow_p = fast_p = self.head
while(slow_p and fast_p and fast_p.next):
slow_p = slow_p.next
365
Chapter 65. Detect and Remove Loop in a Linked List
fast_p = fast_p.next.next
ptr1 = ptr1.next
366
Chapter 65. Detect and Remove Loop in a Linked List
temp = self.head
while(temp):
print temp.data,
temp = temp.next
# Driver program
llist = LinkedList()
llist.push(10)
llist.push(4)
llist.push(15)
llist.push(20)
llist.push(50)
llist.detectAndRemoveLoop()
Output:
#include<stdio.h>
#include<stdlib.h>
367
Chapter 65. Detect and Remove Loop in a Linked List
368
Chapter 65. Detect and Remove Loop in a Linked List
369
Chapter 65. Detect and Remove Loop in a Linked List
detectAndRemoveLoop(head);
Java
class LinkedList {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
370
Chapter 65. Detect and Remove Loop in a Linked List
return 0;
}
371
Chapter 65. Detect and Remove Loop in a Linked List
Python
# Node class
class Node:
class LinkedList:
def detectAndRemoveLoop(self):
slow_p = fast_p = self.head
372
Chapter 65. Detect and Remove Loop in a Linked List
if slow_p == fast_p:
self.removeLoop(slow_p)
373
Chapter 65. Detect and Remove Loop in a Linked List
new_node.next = self.head
self.head = new_node
# Driver program
llist = LinkedList()
llist.push(10)
llist.push(4)
llist.push(15)
llist.push(20)
llist.push(50)
llist.detectAndRemoveLoop()
Output:
374
Chapter 65. Detect and Remove Loop in a Linked List
m + k = (x-2y)*n
So if we start moving both pointers again at same speed such that one pointer (say slow)
begins from head node of linked list and other pointer (say fast) begins from meeting point.
When slow pointer reaches beginning of loop (has made m steps), fast pointer would have
made also moved m steps as they are now moving same pace. Since m+k is a multiple of n
375
Chapter 65. Detect and Remove Loop in a Linked List
and fast starts from k, they would meet at the beginning. Can they meet before also? No
because slow pointer enters the cycle first time after m steps.
C++
struct Node
{
int key;
struct Node *next;
};
376
Chapter 65. Detect and Remove Loop in a Linked List
/* If loop exists */
if (slow == fast)
{
slow = head;
while (slow->next != fast->next)
{
slow = slow->next;
fast = fast->next;
}
detectAndRemoveLoop(head);
return 0;
}
Java
377
Chapter 65. Detect and Remove Loop in a Linked List
class LinkedList {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
slow = slow.next;
fast = fast.next.next;
}
/* If loop exists */
if (slow == fast) {
slow = node;
while (slow.next != fast.next) {
slow = slow.next;
fast = fast.next;
}
378
Chapter 65. Detect and Remove Loop in a Linked List
Python
# Node class
class Node:
class LinkedList:
379
Chapter 65. Detect and Remove Loop in a Linked List
def __init__(self):
self.head = None
def detectAndRemoveLoop(self):
if self.head is None :
return
if self.head.next is None :
return
slow = self.head
fast = self.head
# if loop exists
if slow == fast :
slow = self.head
while (slow.next != fast.next):
slow = slow.next
fast = fast.next
380
Chapter 65. Detect and Remove Loop in a Linked List
print temp.data,
temp = temp.next
# Driver program
llist = LinkedList()
llist.head = Node(50)
llist.head.next = Node(20)
llist.head.next.next = Node(15)
llist.head.next.next.next = Node(4)
llist.head.next.next.next.next = Node(10)
llist.detectAndRemoveLoop()
Output:
struct Node
{
int key;
struct Node *next;
};
381
Chapter 65. Detect and Remove Loop in a Linked List
temp->next = NULL;
return temp;
}
382
Chapter 65. Detect and Remove Loop in a Linked List
head->next->next->next->next->next = head->next->next;
//printList(head);
hashAndRemove(head);
return 0;
}
Source
https://www.geeksforgeeks.org/detect-and-remove-loop-in-a-linked-list/
383
Chapter 66
384
Chapter 66. Detect loop in a linked list
};
h = h->next;
}
return false;
}
push(&head, 20);
385
Chapter 66. Detect loop in a linked list
push(&head, 4);
push(&head, 15);
push(&head, 10);
if (detectLoop(head))
cout << "Loop found";
else
cout << "No Loop";
return 0;
}
// This code is contributed by Geetanjali
Java
386
Chapter 66. Detect loop in a linked list
h = h.next;
}
return false;
}
llist.push(20);
llist.push(4);
llist.push(15);
llist.push(10);
if (detectLoop(head))
System.out.println("Loop found");
else
System.out.println("No Loop");
}
}
Python3
387
Chapter 66. Detect loop in a linked list
# Node class
class Node:
# Constructor to initialize
# the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def detectLoop(self):
s = set()
temp=self.head
while (temp):
388
Chapter 66. Detect loop in a linked list
temp = temp.next
return False
if( llist.detectLoop()):
print ("Loop found")
else :
print ("No Loop ")
Output :
Loop Found
C/C++
389
Chapter 66. Detect loop in a linked list
390
Chapter 66. Detect loop in a linked list
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 10);
return 0;
}
Java
int detectLoop()
{
Node slow_p = head, fast_p = head;
while (slow_p != null && fast_p != null && fast_p.next != null) {
slow_p = slow_p.next;
391
Chapter 66. Detect loop in a linked list
fast_p = fast_p.next.next;
if (slow_p == fast_p) {
System.out.println("Found loop");
return 1;
}
}
return 0;
}
llist.push(20);
llist.push(4);
llist.push(15);
llist.push(10);
llist.detectLoop();
}
}
/* This code is contributed by Rajat Mishra. */
Python
# Node class
class Node:
class LinkedList:
392
Chapter 66. Detect loop in a linked list
new_node.next = self.head
self.head = new_node
def detectLoop(self):
slow_p = self.head
fast_p = self.head
while(slow_p and fast_p and fast_p.next):
slow_p = slow_p.next
fast_p = fast_p.next.next
if slow_p == fast_p:
print "Found Loop"
return
Output:
Found loop
393
Chapter 66. Detect loop in a linked list
Source
https://www.geeksforgeeks.org/detect-loop-in-a-linked-list/
394
Chapter 67
Explanation :
First, after doubling the first element and making
second element 0 before all zeros.
8 -> 0 -> 0 -> 2 -> 3 -> 4 -> 6 -> 0
-> 0 -> 4 ->
Next :
8 -> 6 -> 5 -> 6 -> 0 -> 0 -> 0 ->
0 -> 0 -> 0 -> 0 ->
Traverse through the linked list, and wherever there are two adjacent same data of nodes
395
Chapter 67. Double elements and append zeros in linked list
before a 0 (e.g. 4 -> 4 -> 0), then, double first element and make another as 0 (e.g. 8 -> 0
-> 0 ->). Finally, traverse the linked list and linearly point all the zeros to tail.
// Constructor
public Node(int data)
{
this.data = data;
next = null;
}
}
if (head.next.next.next != null)
head = head.next.next.next;
396
Chapter 67. Double elements and append zeros in linked list
else
return;
}
else
head = head.next;
397
Chapter 67. Double elements and append zeros in linked list
}
else
prev = curr;
return head;
}
// Driver code
public static void main(String[] args)
{
398
Chapter 67. Double elements and append zeros in linked list
head = doubleAndAppend0(head);
Output :
Source
https://www.geeksforgeeks.org/double-elements-and-append-zeros-in-linked-list/
399
Chapter 68
400
Chapter 68. Doubly Circular Linked List | Set 1 (Introduction and Insertion)
• List initially contain some nodes, start points to first node of the List:
A node(Say M) is inserted with data = 7, so previous pointer of M points to last
node, next pointer of M points to first node and last node’s next pointer points
to this M node and first node’s previous pointer points to this M node.
401
Chapter 68. Doubly Circular Linked List | Set 1 (Introduction and Insertion)
402
Chapter 68. Doubly Circular Linked List | Set 1 (Introduction and Insertion)
2. Insertion at the beginning of the list: To insert a node at the beginning of the
list, create a node(Say T) with data = 5, T next pointer points to first node of the list,
T previous pointer points to last node the list, last node’s next pointer points to this
T node, first node’s previous pointer also points this T node and at last don’t forget
to shift ‘Start’ pointer to this T node.
403
Chapter 68. Doubly Circular Linked List | Set 1 (Introduction and Insertion)
3. Insertion in between the nodes of the list: To insert a node in between the list,
two data values are required one after which new node will be inserted and another is
the data of the new node.
Following is a complete program that uses all of the above methods to create a circular
doubly linked list.
404
Chapter 68. Doubly Circular Linked List | Set 1 (Introduction and Insertion)
// Structure of a Node
struct Node
{
int data;
struct Node *next;
struct Node *prev;
};
405
Chapter 68. Doubly Circular Linked List | Set 1 (Introduction and Insertion)
406
Chapter 68. Doubly Circular Linked List | Set 1 (Introduction and Insertion)
{
struct Node *temp = start;
407
Chapter 68. Doubly Circular Linked List | Set 1 (Introduction and Insertion)
display(start);
return 0;
}
Output:
• List can be traversed from both the directions i.e. from head to tail or from tail to
head.
• Jumping from head to tail or from tail to head is done in constant time O(1).
• Circular Doubly Linked Lists are used for implementation of advanced data structures
like Fibonacci Heap.
Disadvantages
Source
https://www.geeksforgeeks.org/doubly-circular-linked-list-set-1-introduction-and-insertion/
408
Chapter 69
Case 2:List initially contain some nodes, start points to first node of the List
1. If the list is not empty then we define two pointers curr and prev_1 and initialize
the pointer curr points to first node of the list and prev_1 = NULL.
2. Traverse the list using curr pointer to find the node to be deleted and before moving
curr to next node, every time set prev_1 = curr.
3. If the node is found, check if it is the only node in the list. If yes, set start = NULL
and free the node pointing by curr.
4. If the list has more than one node, check if it is the first node of the list. Condition
to check this is (curr == start). If yes, then move prev_1 to the last node(prev_1
= start -> prev). After prev_1 reaches the last node, set start = start -> next and
prev_1 -> next = start and start -> prev = prev_1. Free the node pointing by curr.
5. If curr is not first node, we check if it is the last node in the list. Condition to check
this is (curr -> next == start). If yes, set prev_1 -> next = start and start -> prev
= prev_1. Free the node pointing by curr.
6. If the node to be deleted is neither the first node nor the last node, declare one more
pointer temp and initialize the pointer temp points to next of curr pointer (temp =
curr->next). Now set, prev_1 -> next = temp and temp ->prev = prev_1. Free the
node pointing by curr.
409
Chapter 69. Doubly Circular Linked List | Set 2 (Deletion)
• If the given key(Say 4) matches with first node of the list(Step 4):
• If the given key(Say 8) matches with last node of the list(Step 5):
410
Chapter 69. Doubly Circular Linked List | Set 2 (Deletion)
• If the given key(Say 6) matches with middle node of the list(Step 6):
// Structure of a Node
411
Chapter 69. Doubly Circular Linked List | Set 2 (Deletion)
struct Node
{
int data;
struct Node *next;
struct Node *prev;
};
412
Chapter 69. Doubly Circular Linked List | Set 2 (Deletion)
return;
prev_1 = curr;
curr = curr -> next;
}
413
Chapter 69. Doubly Circular Linked List | Set 2 (Deletion)
free(curr);
}
else
{
// create new pointer, points to next of curr node
struct Node *temp = curr -> next;
414
Chapter 69. Doubly Circular Linked List | Set 2 (Deletion)
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/doubly-circular-linked-list-set-2-deletion/
415
Chapter 70
416
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
Java
Python3
Following are advantages/disadvantages of doubly linked list over singly linked list.
Advantages over singly linked list
1) A DLL can be traversed in both forward and backward direction.
2) The delete operation in DLL is more efficient if pointer to the node to be deleted is given.
3) We can quickly insert a new node before a given node.
In singly linked list, to delete a node, pointer to the previous node is needed. To get this
previous node, sometimes the list is traversed. In DLL, we can get the previous node using
previous pointer.
Disadvantages over singly linked list
1) Every node of DLL Require extra space for an previous pointer. It is possible to imple-
ment DLL with single pointer though (See thisand this).
2) All operations require an extra pointer previous to be maintained. For example, in in-
sertion, we need to modify previous pointers together with next pointers. For example in
following functions for insertions at different positions, we need 1 or 2 extra steps to set
previous pointer.
Insertion
A node can be added in four ways
1) At the front of the DLL
2) After a given node.
417
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
418
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
new_node->prev = NULL;
Java
Python3
419
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
Four steps of the above five steps are same as the 4 steps used for inserting at the front in
singly linked list. The only extra step is to change previous of head.
2) Add a node after a given node.: (A 7 steps process)
We are given pointer to a node as prev_node, and the new node is inserted after the given
node.
/* Given a node as prev_node, insert a new node after the given node */
void insertAfter(struct Node* prev_node, int new_data)
{
/*1. check if the given prev_node is NULL */
if (prev_node == NULL) {
printf("the given previous node cannot be NULL");
return;
}
420
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
Java
/* Given a node as prev_node, insert a new node after the given node */
public void InsertAfter(Node prev_Node, int new_data)
{
/* 2. allocate node
* 3. put in the data */
Node new_node = new Node(new_data);
Python3
421
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
Five of the above steps step process are same as the 5 steps used for inserting after a given
node in singly linked list. The two extra steps are needed to change previous pointer of new
node and previous pointer of new node’s next node.
3) Add a node at the end: (7 steps process)
The new node is always added after the last node of the given Linked List. For example
if the given DLL is 510152025 and we add an item 30 at the end, then the DLL becomes
51015202530.
Since a Linked List is typically represented by the head of it, we have to traverse the list
till end and then change the next of last node to new node.
422
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
423
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
return;
}
Java
Python3
424
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
Six of the above 7 steps are same as the 6 steps used for inserting after a given node in
singly linked list. The one extra step is needed to change previous pointer of new node.
4) Add a node before a given node:
Steps
Let the pointer to this given node be next_node and the data of the new node to be added
as new_data.
1. Check if the next_node is NULL or not. If it’s NULL, return from the function
because any new node can not be added before a NULL
2. Allocate memory for the new node, let it be called new_node
3. Set new_node->data = new_data
4. Set the previous pointer of this new_node as the previous node of the next_node,
new_node->prev = next_node->prev
5. Set the previous pointer of the next_node as the new_node, next_node->prev =
new_node
6. Set the next pointer of this new_node as the next_node, new_node->next =
next_node;
7. If the previous node of the new_node is not NULL, then set the next pointer of this
previous node as new_node, new_node->prev->next = new_node
425
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
C++
new_node->data = new_data;
new_node->next = (*head_ref);
new_node->prev = NULL;
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
(*head_ref) = new_node;
}
/* Given a node as next_node, insert a new node before the given node */
void insertBefore(struct Node* next_node, int new_data)
{
/*1. check if the given new_node is NULL */
if (next_node == NULL) {
printf("the given next node cannot be NULL");
return;
}
426
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
// This function prints contents of linked list starting from the given node
void printList(struct Node* node)
{
struct Node* last;
printf("\nTraversal in forward direction \n");
while (node != NULL) {
printf(" %d ", node->data);
last = node;
node = node->next;
}
push(&head, 1);
427
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
push(&head, 4);
getchar();
return 0;
}
Output:
428
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
/* Given a node as prev_node, insert a new node after the given node */
void insertAfter(struct Node* prev_node, int new_data)
{
/*1. check if the given prev_node is NULL */
if (prev_node == NULL) {
printf("the given previous node cannot be NULL");
return;
}
429
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
return;
}
// This function prints contents of linked list starting from the given node
void printList(struct Node* node)
{
struct Node* last;
printf("\nTraversal in forward direction \n");
while (node != NULL) {
printf(" %d ", node->data);
last = node;
node = node->next;
}
430
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
getchar();
return 0;
}
Java
431
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
/* Given a node as prev_node, insert a new node after the given node */
public void InsertAfter(Node prev_Node, int new_data)
{
/* 2. allocate node
* 3. put in the data */
Node new_node = new Node(new_data);
432
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
{
/* 1. allocate node
* 2. put in the data */
Node new_node = new Node(new_data);
// This function prints contents of linked list starting from the given node
public void printlist(Node node)
{
Node last = null;
System.out.println("Traversal in forward Direction");
while (node != null) {
System.out.print(node.data + " ");
last = node;
node = node.next;
}
System.out.println();
System.out.println("Traversal in reverse direction");
while (last != null) {
System.out.print(last.data + " ");
last = last.prev;
}
}
433
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
Python
434
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
# 1. Allocates node
# 2. Put the data in it
new_node = Node(new_data)
435
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
# 1. Allocates node
# 2. Put in the data
new_node = Node(new_data)
return
436
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
llist = DoublyLinkedList()
# Insert 8, after 7.
# So linked list becomes 1->7->8->6->4->None
llist.insertAfter(llist.head.next, 8)
Output:
Source
https://www.geeksforgeeks.org/doubly-linked-list/
437
Chapter 71
Examples:
Input : 5 4 3 2 1
Output : 1 4 3 2 5
Input : 6 1 2 3 4 5 6 7 8 9
Output : 9 1 2 3 4 5 6 7 8 6
438
Chapter 71. Exchange first and last nodes in Circular Linked List
We first find pointer to previous of last node. Let this node be p. Now we change next links
so that the last and first nodes are swapped.
struct Node
{
int data;
struct Node *next;
};
return head;
}
return head;
}
439
Chapter 71. Exchange first and last nodes in Circular Linked List
} while(p != head);
}
return head;
}
// Driven Program
int main()
{
int i;
struct Node *head = NULL;
440
Chapter 71. Exchange first and last nodes in Circular Linked List
return 0;
}
Output:
List Before: 6 1 2 3 4 5
List After: 5 1 2 3 4 6
Source
https://www.geeksforgeeks.org/exchange-first-last-node-circular-linked-list/
441
Chapter 72
Output:
Doubly Linked List
785910
Modified Tree:
1
/ \
2 3
/ \
4 6
We need to traverse all leaves and connect them by changing their left and right pointers.
442
Chapter 72. Extract Leaves of a Binary Tree in a Doubly Linked List
We also need to remove them from Binary Tree by changing left or right pointers in parent
nodes. There can be many ways to solve this. In the following implementation, we add
leaves at the beginning of current linked list and update head of the list using pointer to
head pointer. Since we insert at the beginning, we need to process leaves in reverse order.
For reverse order, we first traverse the right subtree then the left subtree. We use return
values to update left or right pointers in parent nodes.
C
// Main function which extracts all leaves from given Binary Tree.
// The function returns new root of Binary Tree (Note that root may change
// if Binary Tree has only one node). The function also sets *head_ref as
// head of doubly linked list. left pointer of tree is used as prev in DLL
// and right pointer is used as next
struct Node* extractLeafList(struct Node *root, struct Node **head_ref)
{
// Base cases
if (root == NULL) return NULL;
443
Chapter 72. Extract Leaves of a Binary Tree in a Doubly Linked List
return root;
}
444
Chapter 72. Extract Leaves of a Binary Tree in a Doubly Linked List
root->right->right->right = newNode(10);
Java
Node(int item)
{
data = item;
right = left = null;
}
}
445
Chapter 72. Extract Leaves of a Binary Tree in a Doubly Linked List
head = root;
prev = root;
}
else
{
prev.right = root;
root.left = prev;
prev = root;
}
return null;
}
root.left = extractLeafList(root.left);
root.right = extractLeafList(root.right);
return root;
}
446
Chapter 72. Extract Leaves of a Binary Tree in a Doubly Linked List
Python
# Main function which extracts all leaves from given Binary Tree.
# The function returns new root of Binary Tree (Note that
# root may change if Binary Tree has only one node).
# The function also sets *head_ref as head of doubly linked list.
# left pointer of tree is used as prev in DLL
# and right pointer is used as next
def extractLeafList(root):
# Base Case
if root is None:
return None
447
Chapter 72. Extract Leaves of a Binary Tree in a Doubly Linked List
return root
def printList(head):
while(head):
if head.data is not None:
print head.data,
head = head.right
448
Chapter 72. Extract Leaves of a Binary Tree in a Doubly Linked List
root = extractLeafList(root)
Output:
Time Complexity: O(n), the solution does a single traversal of given Binary Tree.
This article is contributed by Chandra Prakash. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/connect-leaves-doubly-linked-list/
449
Chapter 73
For example, the function should return 5 for linked list 1->3->1->2->1.
Iterative Solution
1) Initialize count as 0
2) Initialize a node pointer, current = head.
3) Do following while current is not NULL
a) current = current -> next
b) count++;
4) Return count
Following are C/C++, Java and Python implementations of above algorithm to find count
of nodes.
450
Chapter 73. Find Length of a Linked List (Iterative and Recursive)
C/C++
451
Chapter 73. Find Length of a Linked List (Iterative and Recursive)
Java
452
Chapter 73. Find Length of a Linked List (Iterative and Recursive)
Python
# Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
453
Chapter 73. Find Length of a Linked List (Iterative and Recursive)
self.head = None
Output:
count of nodes is 5
Recursive Solution
454
Chapter 73. Find Length of a Linked List (Iterative and Recursive)
int getCount(head)
1) If head is NULL, return 0.
2) Else return 1 + getCount(head->next)
Following are C/C++, Java and Python implementations of above algorithm to find count
of nodes.
C/C++
455
Chapter 73. Find Length of a Linked List (Iterative and Recursive)
Java
456
Chapter 73. Find Length of a Linked List (Iterative and Recursive)
Python
# Node class
457
Chapter 73. Find Length of a Linked List (Iterative and Recursive)
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
458
Chapter 73. Find Length of a Linked List (Iterative and Recursive)
llist.push(1)
print 'Count of nodes is :',llist.getCount()
Output:
count of nodes is 5
This article is contributed by Ravi. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/find-length-of-a-linked-list-iterative-and-recursive/
459
Chapter 74
Find a triplet from three linked lists with sum equal to a given number - GeeksforGeeks
Given three linked lists, say a, b and c, find one node from each list such that the sum of
the values of the nodes is equal to a given number.
For example, if the three linked lists are 12->6->29, 23->5->8 and 90->20->59, and the
given number is 101, the output should be tripel “6 5 90”.
In the following solutions, size of all three linked lists is assumed same for simplicity of
analysis. The following solutions work for linked lists of different sizes also.
A simple method to solve this problem is to run three nested loops. The outermost loop
picks an element from list a, the middle loop picks an element from b and the innermost
loop picks from c. The innermost loop also checks whether the sum of values of current
nodes of a, b and c is equal to given number. The time complexity of this method will be
O(n^3).
Sorting can be used to reduce the time complexity to O(n*n). Following are the detailed
steps.
1) Sort list b in ascending order, and list c in descending order.
2) After the b and c are sorted, one by one pick an element from list a and find the pair
by traversing both b and c. See isSumSorted() in the following code. The idea is similar to
Quadratic algorithm of 3 sum problem.
Following code implements step 2 only. The solution can be easily modified for unsorted
lists by adding the merge sort code discussed here.
C/C++
460
Chapter 74. Find a triplet from three linked lists with sum equal to a given number
461
Chapter 74. Find a triplet from three linked lists with sum equal to a given number
{
// If this a triplet with given sum, print
// it and return true
int sum = a->data + b->data + c->data;
if (sum == givenNumber)
{
printf ("Triplet Found: %d %d %d ", a->data,
b->data, c->data);
return true;
}
462
Chapter 74. Find a triplet from three linked lists with sum equal to a given number
return 0;
}
Java
463
Chapter 74. Find a triplet from three linked lists with sum equal to a given number
else
c = c.next;
}
a = a.next;
}
System.out.println("No Triplet found");
return false;
}
464
Chapter 74. Find a triplet from three linked lists with sum equal to a given number
Output:
Triplet Found: 15 2 8
Time complexity: The linked lists b and c can be sorted in O(nLogn) time using Merge
Sort (See this). The step 2 takes O(n*n) time. So the overall time complexity is O(nlogn)
+ O(nlogn) + O(n*n) = O(n*n).
In this approach, the linked lists b and c are sorted first, so their original order will be lost.
If we want to retain the original order of b and c, we can create copy of b and c.
This article is compiled by Abhinav Priyadarshi and reviewed by GeeksforGeeks team.
Please write comments if you find anything incorrect, or you want to share more information
about the topic discussed above
Source
https://www.geeksforgeeks.org/find-a-triplet-from-three-linked-lists-with-sum-equal-to-a-given-number/
465
Chapter 75
Input :
10 15 20 25 12
10 12 13 15
10 12 15 24 25 26
Output : 10 12 15
Input :
1 2 3 4 5
1 2 3 4 6 9 8
1 2 4 5 10
Output : 1 2 4
Method 1 : (Simple)
Use three-pointers to iterate the given three linked lists and if any element common print
that element.
Time complexity of the above solution will be O(N*N*N)
Method 2 : (Use Merge Sort)
In this method, we first sort the three lists and then we traverse the sorted lists to get the
intersection.
Following are the steps to be followed to get intersection of three lists:
1) Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this
post for details of this step.
466
Chapter 75. Find common elements in three linked lists
2) Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this
post for details of this step.
3) Sort the third Linked List using merge sort. This step takes O(pLogp) time. Refer this
post for details of this step.
3) Linearly scan three sorted lists to get the intersection. This step takes O(m + n + p)
time. This step can be implemented using the same algorithm as sorted arrays algorithm
discussed here.
Time complexity of this method is O(mLogm + nLogn + plogp) which is better than method
1’s time complexity.
Method 3 : (Hashing)
Following are the steps to be followed to get intersection of three lists using hashing:
1) Create an empty hash table. Iterate through the first linked list and mark all the element
frequency as 1 in the hash table. This step takes O(m) time.
2) Iterate through the second linked list and if current element frequency is 1 in hash table
mark it as 2. This step takes O(n) time.
3) Iterate the third linked list and if the current element frequency is 2 in hash table mark
it as 3. This step takes O(p) time.
4) Now iterate first linked list again to check the frequency of elements. if an element with
frequency three exist in hash table, it will be present in the intersection of three linked lists.
This step takes O(m) time.
Time complexity of this method is O(m + n + p) which is better than time complexity of
method 1 and 2.
Below is the C++ implementation of the above idea.
467
Chapter 75. Find common elements in three linked lists
// set frequency by 1
hash[p->data] = 1;
p = p->next;
}
468
Chapter 75. Find common elements in three linked lists
// Driver code
int main()
{
// first list
struct Node* head1 = NULL;
push(&head1, 20);
push(&head1, 5);
push(&head1, 15);
push(&head1, 10);
// second list
struct Node* head2 = NULL;
push(&head2, 10);
push(&head2, 20);
push(&head2, 15);
push(&head2, 8);
// third list
struct Node* head3 = NULL;
push(&head3, 10);
push(&head3, 2);
push(&head3, 15);
push(&head3, 20);
return 0;
}
Output:
10 15 20
Source
https://www.geeksforgeeks.org/find-common-elements-in-three-linked-lists/
469
Chapter 76
We have discussed Floyd’s loop detection algorithm. Below are steps to find first node of
loop.
1. If a loop is found, initialize slow pointer to head, let fast pointer be at its position.
2. Move both slow and fast pointers one node at a time.
3. The point at which they meet is the start of the loop.
struct Node {
int key;
struct Node* next;
};
470
Chapter 76. Find first node of loop in a linked list
471
Chapter 76. Find first node of loop in a linked list
return slow;
}
return 0;
}
Output:
472
Chapter 76. Find first node of loop in a linked list
m + k = (x-2y)*n
So if we start moving both pointers again at same speed such that one pointer (say slow)
begins from head node of linked list and other pointer (say fast) begins from meeting point.
When slow pointer reaches beginning of loop (has made m steps), fast pointer would have
made also moved m steps as they are now moving same pace. Since m+k is a multiple of n
and fast starts from k, they would meet at the beginning. Can they meet before also? No
because slow pointer enters the cycle first time after m steps.
473
Chapter 76. Find first node of loop in a linked list
Source
https://www.geeksforgeeks.org/find-first-node-of-loop-in-a-linked-list/
474
Chapter 77
Find kth node from Middle towards Head of a Linked List - GeeksforGeeks
Given a Linked List and a number K. The task is to print the value of the K-th node from
the middle towards the beginning of the List. If no such element exists, then print “-1”.
Note: Position of middle node is: (n/2)+1, where n is the total number of nodes in the list.
Examples:
Traverse the List from beginning to end and count the total number of nodes. Now, suppose
is the total number of nodes in the List. Therefore, the middle node will be at the position
(n/2)+1. Now, the task remains to print the node at (n/2 + 1 – k)th position from the head
of the List.
Below is the implementation of the above idea:
#include <bits/stdc++.h>
475
Chapter 77. Find kth node from Middle towards Head of a Linked List
476
Chapter 77. Find kth node from Middle towards Head of a Linked List
else {
struct Node* current = head_ref;
// Driver code
int main()
{
// start with empty list
struct Node* head = NULL;
int k = 2;
return 0;
}
Output:
477
Chapter 77. Find kth node from Middle towards Head of a Linked List
Source
https://www.geeksforgeeks.org/find-kth-node-from-middle-towards-head-of-a-linked-list/
478
Chapter 78
We know that Floyd’s Cycle detection algorithm terminates when fast and slow pointers
meet at a common point. We also know that this common point is one of the loop nodes
(2 or 3 or 4 or 5 in the above diagram). We store the address of this in a pointer variable
say ptr2. Then we start from the head of the Linked List and check for nodes one by one
if they are reachable from ptr2. When we find a node that is reachable, we know that this
node is the starting node of the loop in Linked List and we can get pointer to the previous
of this node.
479
Chapter 78. Find length of loop in linked list
{
int data;
struct Node* next;
};
480
Chapter 78. Find length of loop in linked list
return 0;
}
Output :
Related Articles :
Detect loop in a linked list
Detect and Remove Loop in a Linked List
Improved By : subtleseeker
Source
https://www.geeksforgeeks.org/find-length-of-loop-in-linked-list/
481
Chapter 79
Input : 1->2->3->4->5
Output : 3
Input : 1->2->3->4->5->6
Output : 4
We have already discussed Iterative Solution. In this post iterative solution is discussed.
Count total number of nodes in the list in recursive manner and do half of this, suppose this
value is n. Then rolling back through recursion decrement n by one for each call. Return
the node where n is zero.
482
Chapter 79. Find middle of singly linked list Recursively
*n = *n + 1;
midpoint_util(head->next, n, mid);
// Final answer
*mid = head;
}
}
int main()
{
Node* head = newLNode(1);
head->next = newLNode(2);
head->next->next = newLNode(3);
head->next->next->next = newLNode(4);
483
Chapter 79. Find middle of singly linked list Recursively
head->next->next->next->next = newLNode(5);
Node* result = midpoint(head);
cout << result->data << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/find-middle-singly-linked-list-recursively/
484
Chapter 80
1. Take a pointer modularNode and initialize it with NULL. Traverse the linked list.
2. For every i%k=0, update modularNode.
C++
485
Chapter 80. Find modular node in a linked list
i++;
}
return modularNode;
}
Java
486
Chapter 80. Find modular node in a linked list
i++;
}
return modularNode;
}
487
Chapter 80. Find modular node in a linked list
Output:
Modular node is 4
Source
https://www.geeksforgeeks.org/find-modular-node-linked-list/
488
Chapter 81
Find pair for given sum in a sorted singly linked without extra space - GeeksforGeeks
Given a sorted singly linked list and a value x, the task is to find pair whose sum is equal
to x. We are not allowed to use any extra space and expected time complexity is O(n).
Examples:
• First we need to convert our singly linked list into doubly linked list. Here we are given
singly linked list structure node which have only next pointer not prev pointer, so
to convert our singly linked list into doubly linked list we use memory efficient doubly
linked list ( XOR linked list ).
489
Chapter 81. Find pair for given sum in a sorted singly linked without extra space
• In XOR linked list each next pointer of singly linked list contains XOR of next and
prev pointer.
• After converting singly linked list into doubly linked list we initialize two pointers
variables to find the candidate elements in the sorted doubly linked list. Initialize
first with start of doubly linked list i.e; first = head and initialize second with last
node of doubly linked list i.e; second = last_node.
• Here we don’t have random access, so to initialize pointer, we traverse the list till last
node and assign last node to second.
• If current sum of first and second is less than x, then we move first in forward
direction. If current sum of first and second element is greater than x, then we move
second in backward direction.
• Loop termination conditions are also different from arrays. The loop terminates when
either of two pointers become NULL, or they cross each other (first=next_node), or
they become same (first == second).
490
Chapter 81. Find pair for given sum in a sorted singly linked without extra space
491
Chapter 81. Find pair for given sum in a sorted singly linked without extra space
flag = true;
492
Chapter 81. Find pair for given sum in a sorted singly linked without extra space
Output:
493
Chapter 81. Find pair for given sum in a sorted singly linked without extra space
If linked list is not sorted, then we can sort the list as a first step. But in that case overall
time complexity would become O(n Log n). We can use Hashing in such cases if extra space
is not a constraint. The hashing based solution is same as method 2 here.
Source
https://www.geeksforgeeks.org/find-pair-given-sum-sorted-singly-linked-without-extra-space/
494
Chapter 82
• Initialize two pointer variables to find the candidate elements in the sorted doubly
linked list.Initialize first with start of doubly linked list i.e; first=head and initialize
second with last node of doubly linked list i.e; second=last_node.
• We initialize first and second pointers as first and last nodes. Here we don’t have
random access, so to find second pointer, we traverse the list to initialize second.
• If current sum of first and second is less than x, then we move first in forward
direction. If current sum of first and second element is greater than x, then we move
second in backward direction.
• Loop termination conditions are also different from arrays. The loop terminates when
either of two pointers become NULL, or they cross each other (second->next = first),
or they become same (first == second)
495
Chapter 82. Find pairs with given sum in doubly linked list
496
Chapter 82. Find pairs with given sum in doubly linked list
second = second->prev;
}
}
// Driver program
int main()
{
struct Node *head = NULL;
insert(&head, 9);
insert(&head, 8);
insert(&head, 6);
insert(&head, 5);
insert(&head, 4);
insert(&head, 2);
insert(&head, 1);
int x = 7;
pairSum(head, x);
return 0;
}
Output:
(6,1)
497
Chapter 82. Find pairs with given sum in doubly linked list
(5,2)
Source
https://www.geeksforgeeks.org/find-pairs-given-sum-doubly-linked-list/
498
Chapter 83
Input : 15 14 13 22 17
Output : Linked list are:
17 -> 22 -> 13 -> 14 -> 15 -> NULL
Maximum element in linked list: 22
Minimum element in linked list: 13
Input : 20 25 23 68 54 13 45
Output : Linked list are:
45 -> 13 -> 54 -> 68 -> 23 -> 25 -> 20 -> NULL
Maximum element in linked list: 68
Minimum element in linked list: 13
The idea is to traverse the linked list while head not equal to NULL and initialise the
max and min variable to INT_MIN and INT_MAX respectively. After that check a
condition that if max value is less then head value then head value is assign to max or min
value is greater then head value then head value is assign to min otherwise head point to
next node. Continue this process until head not equal to NULL.
499
Chapter 83. Find smallest and largest elements in singly linked list
500
Chapter 83. Find smallest and largest elements in singly linked list
head = head->next;
}
return min;
}
501
Chapter 83. Find smallest and largest elements in singly linked list
return 0;
}
Output:
Linked list is :
17 -> 22 -> 13 -> 14 -> 15 -> NULL
Maximum element in linked list: 22
Minimum element in linked list: 13
Source
https://www.geeksforgeeks.org/find-smallest-largest-elements-singly-linked-list/
502
Chapter 84
1. Create an empty DLL. Also create two arrays inDLL[] and repeated[] of size 256.
inDLL is an array of pointers to DLL nodes. repeated[] is a boolean array, repeated[x]
is true if x is repeated two or more times, otherwise false. inDLL[x] contains pointer
to a DLL node if character x is present in DLL, otherwise NULL.
2. Initialize all entries of inDLL[] as NULL and repeated[] as false.
3. To get the first non-repeating character, return character at head of DLL.
4. Following are steps to process a new character ‘x’ in stream.
503
Chapter 84. Find the first non-repeating character from a stream of characters
Note that appending a new node to DLL is O(1) operation if we maintain tail pointer.
Removing a node from DLL is also O(1). So both operations, addition of new character and
finding first non-repeating character take O(1) time.
C/C++
if (*head_ref == NULL)
{
*head_ref = *tail_ref = temp;
return;
}
(*tail_ref)->next = temp;
temp->prev = *tail_ref;
*tail_ref = temp;
}
504
Chapter 84. Find the first non-repeating character from a stream of characters
// Note that the function may change head and tail pointers,
// that is why pointers to these pointers are passed.
void removeNode(struct node **head_ref, struct node **tail_ref,
struct node *temp)
{
if (*head_ref == NULL)
return;
if (*head_ref == temp)
*head_ref = (*head_ref)->next;
if (*tail_ref == temp)
*tail_ref = (*tail_ref)->prev;
if (temp->next != NULL)
temp->next->prev = temp->prev;
if (temp->prev != NULL)
temp->prev->next = temp->next;
delete(temp);
}
void findFirstNonRepeating()
{
// inDLL[x] contains pointer to a DLL node if x is present
// in DLL. If x is not present, then inDLL[x] is NULL
struct node *inDLL[MAX_CHAR];
505
Chapter 84. Find the first non-repeating character from a stream of characters
Java
import java.util.ArrayList;
import java.util.List;
506
Chapter 84. Find the first non-repeating character from a stream of characters
507
Chapter 84. Find the first non-repeating character from a stream of characters
}
//This code is contributed by Sumit Ghosh
Python
def findFirstNonRepeating():
if len(inDLL) != 0:
print "First non-repeating character so far is ",
print str(inDLL[0])
# Driver program
findFirstNonRepeating()
Output:
508
Chapter 84. Find the first non-repeating character from a stream of characters
509
Chapter 84. Find the first non-repeating character from a stream of characters
This article is contributed by Amit Jain. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/find-first-non-repeating-character-stream-characters/
510
Chapter 85
Find the fractional (or n/k - th) node in linked list - GeeksforGeeks
Given a singly linked list and a number k, write a function to find the (n/k)-th element,
where n is the number of elements in the list. We need to consider ceil value in case of
decimals.
Examples:
1. Take two pointers temp and fractionalNode and initialize them with null and head
respectively.
2. For every k jumps of the temp pointer, make one jump of the fractionalNode pointer.
C++
511
Chapter 85. Find the fractional (or n/k – th) node in linked list
else
fractionalNode = fractionalNode->next;
}
i++;
}
return fractionalNode;
}
512
Chapter 85. Find the fractional (or n/k – th) node in linked list
printf("List is ");
printList(head);
return 0;
}
Java
//Constructor
Node (int data){
this.data = data;
}
}
513
Chapter 85. Find the fractional (or n/k – th) node in linked list
// Corner cases
if (k <= 0 || head == null)
return null;
System.out.print("List is ");
printList(head);
514
Chapter 85. Find the fractional (or n/k – th) node in linked list
Output:
List is 1 2 3 4 5
Fractional node is 3
Source
https://www.geeksforgeeks.org/find-fractional-nk-th-node-linked-list/
515
Chapter 86
Input : 10->8->4->23->67->88
Largest node is: 88
Output : 88
Input : 34->2->78->18->120->39->7
Largest node is: 120
Output :120
Approach Used :
1. Initialize the temp and max pointer to head nodes.
2. Traverse the whole list.
3. if temp’s data is greater than max’s data, then put max = temp.
4. move on next node .
516
Chapter 86. Find the largest node in Doubly linked list
/* UTILITY FUNCTIONS */
/* Function to insert a node at the
beginging of the Doubly Linked List */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));
517
Chapter 86. Find the largest node in Doubly linked list
max = temp;
temp = temp->next;
}
return max->data;
}
int main()
{
// Start with the empty list
struct Node* head = NULL;
printf("%d", LargestInDLL(&head));
return 0;
}
Output: 181
Source
https://www.geeksforgeeks.org/find-largest-node-doubly-linked-list/
518
Chapter 87
Method 2:
Traverse linked list using two pointers. Move one pointer by one and other pointer by two.
When the fast pointer reaches end slow pointer will reach middle of the linked list.
C
#include<stdio.h>
#include<stdlib.h>
519
Chapter 87. Find the middle of a given linked list in C and Java
{
struct Node *slow_ptr = head;
struct Node *fast_ptr = head;
if (head!=NULL)
{
while (fast_ptr != NULL && fast_ptr->next != NULL)
{
fast_ptr = fast_ptr->next->next;
slow_ptr = slow_ptr->next;
}
printf("The middle element is [%d]\n\n", slow_ptr->data);
}
}
520
Chapter 87. Find the middle of a given linked list in C and Java
return 0;
}
Java
521
Chapter 87. Find the middle of a given linked list in C and Java
Output:
5->NULL
The middle element is [5]
4->5->NULL
The middle element is [5]
3->4->5->NULL
522
Chapter 87. Find the middle of a given linked list in C and Java
2->3->4->5->NULL
The middle element is [4]
1->2->3->4->5->NULL
The middle element is [3]
Method 3:
Initialize mid element as head and initialize a counter as 0. Traverse the list from head,
while traversing increment the counter and change mid to mid->next whenever the counter
is odd. So the mid will move only half of the total length of the list.
Thanks to Narendra Kangralkar for suggesting this method.
#include<stdio.h>
#include<stdlib.h>
++count;
head = head->next;
}
523
Chapter 87. Find the middle of a given linked list in C and Java
/* allocate node */
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
return 0;
}
Output:
5->NULL
The middle element is [5]
524
Chapter 87. Find the middle of a given linked list in C and Java
4->5->NULL
The middle element is [5]
3->4->5->NULL
The middle element is [4]
2->3->4->5->NULL
The middle element is [4]
1->2->3->4->5->NULL
The middle element is [3]
Source
https://www.geeksforgeeks.org/write-a-c-function-to-print-the-middle-of-the-linked-list/
525
Chapter 88
Find the sum of last n nodes of the given Linked List - GeeksforGeeks
Given a linked list and a number n. Find the sum of last n nodes of the linked list.
Constraints: 0 <= n <= number of nodes in the linked list.
Examples:
Input : 10->6->8->4->12, n = 2
Output : 16
Sum of last two nodes:
12 + 4 = 16
Input : 15->7->9->5->16->14, n = 4
Output : 44
526
Chapter 88. Find the sum of last n nodes of the given Linked List
// accumulate sum
*sum = *sum + head->data;
527
Chapter 88. Find the sum of last n nodes of the given Linked List
return 0;
int sum = 0;
// required sum
return sum;
}
int n = 2;
cout << "Sum of last " << n << " nodes = "
<< sumOfLastN_NodesUtil(head, n);
return 0;
}
Output:
Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(n), if system call stack is being considered.
Method 2 (Iterative approach using user defined stack)
It is an iterative procedure to the recursive approach explained in Method 1 of this post.
Traverses the nodes from left to right. While traversing pushes the nodes to a user defined
stack. Then pops the top n values from the stack and adds them.
528
Chapter 88. Find the sum of last n nodes of the given Linked List
struct Node {
int data;
struct Node* next;
};
stack<int> st;
int sum = 0;
529
Chapter 88. Find the sum of last n nodes of the given Linked List
// required sum
return sum;
}
int n = 2;
cout << "Sum of last " << n << " nodes = "
<< sumOfLastN_NodesUtil(head, n);
return 0;
}
Output:
Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(n), stack size
Method 3 (Reversing the linked list)
Following are the steps:
530
Chapter 88. Find the sum of last n nodes of the given Linked List
int data;
struct Node* next;
};
*head_ref = prev;
}
int sum = 0;
531
Chapter 88. Find the sum of last n nodes of the given Linked List
// required sum
return sum;
}
int n = 2;
cout << "Sum of last " << n << " nodes = "
<< sumOfLastN_NodesUtil(head, n);
return 0;
}
Output:
Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(1)
Method 4 (Using length of linked list)
Following are the steps:
532
Chapter 88. Find the sum of last n nodes of the given Linked List
533
Chapter 88. Find the sum of last n nodes of the given Linked List
// required sum
return sum;
}
int n = 2;
cout << "Sum of last " << n << " nodes = "
<< sumOfLastN_NodesUtil(head, n);
return 0;
}
Output:
534
Chapter 88. Find the sum of last n nodes of the given Linked List
Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(1)
Method 5 (Use of two pointers requires single traversal)
Maintain two pointers – reference pointer and main pointer. Initialize both reference and
main pointers to head. First move reference pointer to n nodes from head and while travers-
ing accumulate node’s data to some variable, say sum. Now move both pointers simultane-
ously until reference pointer reaches to the end of the list and while traversing accumulate
all node’s data to sum pointed by the reference pointer and accumulate all node’s data to
some variable, say temp, pointed by the main pointer. Now, (sum – temp) is the required
sum of the last n nodes.
535
Chapter 88. Find the sum of last n nodes of the given Linked List
// required sum
return (sum - temp);
}
int n = 2;
cout << "Sum of last " << n << " nodes = "
<< sumOfLastN_NodesUtil(head, n);
return 0;
536
Chapter 88. Find the sum of last n nodes of the given Linked List
Output:
Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(1)
Source
https://www.geeksforgeeks.org/find-sum-last-n-nodes-given-linked-list/
537
Chapter 89
Method 1 (Using Two Loops) This is the simple way where two loops are used. Outer
loop is used to pick the elements one by one and inner loop compares the picked element
with rest of the elements. If Element is not equal to other elements than Print that Element.
Time Complexity : O(N * n)
Method 2 (Sorting) : Sort the elements using Merge Sort. O(n Log n). Now Traverse
List in linear time and check if current element is not equal to previous element then Print
O(N)
Please note that this method doesn’t preserve the original order of elements.
Time Complexity: O(NLogN)
Method 3 (Hashing)
We use the concept of Hash table Here, We traverse the link list from head to end. For
every newly encountered element, we put it in the hash table after that we again traverse
list and Print those elements whose frequency is 1.Time Complexity : O(N)
Below is the Implementation of this
538
Chapter 89. Find unique elements in linked list
int count = 0;
for (Node *temp=head; temp!=NULL; temp=temp->next) {
539
Chapter 89. Find unique elements in linked list
int main()
{
struct Node* head = NULL;
Output:
1 2
Source
https://www.geeksforgeeks.org/find-unique-elements-linked-list/
540
Chapter 90
Input :
List1: 10->15->4->20
Lsit2: 8->4->2->10
Output : 10
Input :
List1: 1->2->3->4
Lsit2: 5->6->3->8
Output : 3
We traverse first list and for every node, we search it in second list. As soon as we find an
element in second list, we return it.
541
Chapter 90. First common element in two linked lists
};
// If no common node
return 0;
}
// Driver code
int main()
{
struct Node* head1 = NULL;
push(&head1, 20);
push(&head1, 5);
push(&head1, 15);
push(&head1, 10);
Output:
542
Chapter 90. First common element in two linked lists
10
Source
https://www.geeksforgeeks.org/first-common-element-two-linked-lists/
543
Chapter 91
Input : 10->20->30->10->20->40->30->NULL
Output :First Non-repeating element is 40.
Input :1->1->2->2->3->4->3->4->5->NULL
Output :First Non-repeating element is 5.
Input :1->1->2->2->3->4->3->4->NULL
Output :No NOn-repeating element is found.
544
Chapter 91. First non-repeating in a linked list
};
return -1;
}
545
Chapter 91. First non-repeating in a linked list
Output:
15
Further Optimizations:
The above solution requires two traversals of linked list. In case we have many repeating
elements, we can save one traversal by storing positions also in hash table. Please refer last
method of Given a string, find its first non-repeating character for details.
Source
https://www.geeksforgeeks.org/first-non-repeating-linked-list/
546
Chapter 92
Input :
1
/ \
2 5
/ \ \
3 4 6
Output :
1
\
2
\
3
\
4
\
5
\
6
Input :
547
Chapter 92. Flatten a binary tree into linked list
1
/ \
3 4
/
2
\
5
Output :
1
\
3
\
4
\
2
\
5
Simple Approach: A simple solution is to use Level Order Traversal using Queue. In level
order traversal, keep track of previous node. Make current node as right child of previous
and left of previous node as NULL. This solution requires queue, but question asks to solve
without additional data structure.
Efficient Without Additional Data StructureRecursively look for the node with no
grandchildren and both left and right child in the left sub-tree. Then store node->right in
temp and make node->right=node->left. Insert temp in first node NULL on right of node
by node=node->right. Repeat until it is converted to linked list.
For Example,
548
Chapter 92. Flatten a binary tree into linked list
struct Node {
int key;
Node *left, *right;
};
549
Chapter 92. Flatten a binary tree into linked list
flatten(root);
Output:
550
Chapter 92. Flatten a binary tree into linked list
Source
https://www.geeksforgeeks.org/flatten-a-binary-tree-into-linked-list/
551
Chapter 93
Input:
1
/ \
2 5
/ \ \
3 4 6
Output:
1
\
2
\
3
\
4
\
5
\
6
Input:
1
552
Chapter 93. Flatten a binary tree into linked list | Set-2
/ \
3 4
/
2
\
5
Output:
1
\
3
\
4
\
2
\
5
Approach: An approach using recursion has already been discussed in the previous post.
A pre-order traversal of the binary tree using stack has been implied in this approach. In
this traversal, every time a right child is pushed in the stack, the right child is made equal
to the left child and left child is made equal to NULL. If the right child of the node becomes
NULL, the stack is popped and the right child becomes the popped value from the stack.
The above steps are repeated until the size of the stack is zero or root is NULL.
Below is the implementation of the above approach:
struct Node {
int key;
Node *left, *right;
};
553
Chapter 93. Flatten a binary tree into linked list | Set-2
// Declare a stack
stack<Node*> st;
Node* ans = A;
// Iterate
A = A->right;
}
return ans;
}
// Driver Code
int main()
554
Chapter 93. Flatten a binary tree into linked list | Set-2
{
/* 1
/ \
2 5
/ \ \
3 4 6 */
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/flatten-a-binary-tree-into-linked-list-set-2/
555
Chapter 94
Input:
1 - 2 - 3 - 4
|
7 - 8 - 10 - 12
| | |
9 16 11
| |
14 17 - 18 - 19 - 20
| |
15 - 23 21
|
24
Output:
Linked List to be flattened to
1 - 2 - 7 - 9 - 14 - 15 - 23 - 24 - 8
- 16 - 17 - 18 - 19 - 20 - 21 - 10 -
11 - 12 - 3 - 4
Note : 9 appears before 8 (When we are
at a node, we process down pointer before
right pointer)
556
Chapter 94. Flatten a multi-level linked list | Set 2 (Depth wise)
If we take a closer look, we can notice that this problem is similar to tree to linked list
conversion. We recursively flatten a linked list with following steps.
1) If node is NULL, return NULL.
2) Store next node of current node (used in step 4).
3) Recursively flatten down list. While flattening, keep track of last visited node, so that
the next list can be linked after it.
4) Recursively flatten next list (we get the next list from pointer stored in step 2) and attach
it after last visited node.
Below is C++ implementation of above idea.
557
Chapter 94. Flatten a multi-level linked list | Set 2 (Depth wise)
return node;
}
// Driver code
int main()
{
// Creating above example list
Node* head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
head->next->down = newNode(7);
head->next->down->down = newNode(9);
head->next->down->down->down = newNode(14);
head->next->down->down->down->down
= newNode(15);
head->next->down->down->down->down->next
= newNode(23);
head->next->down->down->down->down->next->down
= newNode(24);
head->next->down->next = newNode(8);
head->next->down->next->down = newNode(16);
head->next->down->next->down->down = newNode(17);
head->next->down->next->down->down->next
= newNode(18);
head->next->down->next->down->down->next->next
= newNode(19);
head->next->down->next->down->down->next->next->next
= newNode(20);
558
Chapter 94. Flatten a multi-level linked list | Set 2 (Depth wise)
head->next->down->next->down->down->next->next->next->down
= newNode(21);
head->next->down->next->next = newNode(10);
head->next->down->next->next->down = newNode(11);
head->next->down->next->next->next = newNode(12);
return 0;
}
Output:
1 2 7 9 14 15 23 24 8 16 17 18 19 20 21 10 11 12 3 4
Source
https://www.geeksforgeeks.org/flatten-a-multi-level-linked-list-set-2-depth-wise/
559
Chapter 95
struct List
{
int data;
struct List *next;
struct List *child;
};
560
Chapter 95. Flatten a multilevel linked list
The problem clearly say that we need to flatten level by level. The idea of solution is, we
start from first level, process all nodes one by one, if a node has a child, then we append the
child at the end of list, otherwise we don’t do anything. After the first level is processed, all
next level nodes will be appended after first level. Same process is followed for the appended
nodes.
1) Take "cur" pointer, which will point to head of the fist level of the list
2) Take "tail" pointer, which will point to end of the first level of the list
3) Repeat the below procedure while "curr" is not NULL.
I) if current node has a child then
a) append this new child list to the "tail"
tail->next = cur->child
b) find the last node of new child list and update "tail"
tmp = cur->child;
while (tmp->next != NULL)
tmp = tmp->next;
tail = tmp;
II) move to the next node. i.e. cur = cur->next
// A linked list node has data, next pointer and child pointer
struct Node
{
int data;
struct Node *next;
struct Node *child;
};
int i;
561
Chapter 95. Flatten a multilevel linked list
// This function creates the input list. The created list is same
// as shown in the above figure
struct Node *createList(void)
{
int arr1[] = {10, 5, 12, 7, 11};
int arr2[] = {4, 20, 13};
int arr3[] = {17, 6};
int arr4[] = {9, 8};
int arr5[] = {19, 15};
int arr6[] = {2};
int arr7[] = {16};
int arr8[] = {3};
562
Chapter 95. Flatten a multilevel linked list
head1->child = head2;
head1->next->next->next->child = head3;
head3->child = head4;
head4->child = head5;
head2->next->child = head6;
head2->next->next->child = head7;
head7->child = head8;
/* Return head pointer of first linked list. Note that all nodes are
reachable from head1 */
return head1;
}
563
Chapter 95. Flatten a multilevel linked list
}
}
Java
// Java program to flatten linked list with next and child pointers
class LinkedList {
class Node {
int data;
Node next, child;
Node(int d) {
data = d;
next = child = null;
}
}
int i;
for (i = 0; i < n; ++i) {
if (node == null) {
node = p = new Node(arr[i]);
} else {
p.next = new Node(arr[i]);
p = p.next;
}
p.next = p.child = null;
}
564
Chapter 95. Flatten a multilevel linked list
return node;
}
Node createList() {
int arr1[] = new int[]{10, 5, 12, 7, 11};
int arr2[] = new int[]{4, 20, 13};
int arr3[] = new int[]{17, 6};
int arr4[] = new int[]{9, 8};
int arr5[] = new int[]{19, 15};
int arr6[] = new int[]{2};
int arr7[] = new int[]{16};
int arr8[] = new int[]{3};
/* Return head pointer of first linked list. Note that all nodes are
reachable from head1 */
return head1;
}
565
Chapter 95. Flatten a multilevel linked list
/*Base case*/
if (node == null) {
return;
}
566
Chapter 95. Flatten a multilevel linked list
Output:
10 5 12 7 11 4 20 13 17 6 2 16 9 8 3 19 15
Time Complexity: Since every node is visited at most twice, the time complexity is O(n)
where n is the number of nodes in given linked list.
This article is compiled by Narendra Kangralkar. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/flatten-a-linked-list-with-next-and-child-pointers/
567
Chapter 96
Write a function flatten() to flatten the lists into a single linked list. The flattened linked
list should also be sorted. For example, for the above input list, output list should be
5->7->8->10->19->20->22->28->30->35->40->45->50.
The idea is to use Merge() process of merge sort for linked lists. We use merge() to merge
lists one by one. We recursively merge() the current list with already flattened list.
The down pointer is used to link nodes of the flattened list.
Following are C and Java implementations.
C/C++
568
Chapter 96. Flattening a Linked List
569
Chapter 96. Flattening a Linked List
if (b == NULL)
return a;
return result;
}
570
Chapter 96. Flattening a Linked List
push( &root, 30 );
push( &root, 8 );
push( &root, 7 );
push( &root, 5 );
return 0;
}
Java
571
Chapter 96. Flattening a Linked List
{
// if first linked list is empty then second
// is the answer
if (a == null) return b;
else
{
result = b;
result.down = merge(a, b.down);
}
return result;
}
// now merge
root = merge(root, root.right);
572
Chapter 96. Flattening a Linked List
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(data);
void printList()
{
Node temp = head;
while (temp != null)
{
System.out.print(temp.data + " ");
temp = temp.down;
}
System.out.println();
}
573
Chapter 96. Flattening a Linked List
L.printList();
}
} /* This code is contributed by Rajat Mishra */
Output:
5 7 8 10 19 20 20 22 30 35 40 45 50
Improved By : kaviarasu
Source
https://www.geeksforgeeks.org/flattening-a-linked-list/
574
Chapter 97
575
Chapter 97. Function to check if a singly linked list is palindrome
4) Construct the original linked list by reversing the second half again and attaching it back
to the first half
To divide the list in two halves, method 2 of thispost is used.
When number of nodes are even, the first and second half contain exactly half nodes. The
challenging thing in this method is to handle the case when number of nodes are odd. We
don’t want the middle node as part of any of the lists as we are going to compare them for
equality. For odd case, we use a separate variable ‘midnode’.
C
576
Chapter 97. Function to check if a singly linked list is palindrome
/* fast_ptr would become NULL when there are even elements in list.
And not NULL for odd elements. We need to skip the middle node
for odd case and store it somewhere so that we can restore the
original list*/
if (fast_ptr != NULL)
{
midnode = slow_ptr;
slow_ptr = slow_ptr->next;
}
// Now reverse the second half and compare it with first half
second_half = slow_ptr;
prev_of_slow_ptr->next = NULL; // NULL terminate first half
reverse(&second_half); // Reverse the second half
res = compareLists(head, second_half); // compare
577
Chapter 97. Function to check if a singly linked list is palindrome
578
Chapter 97. Function to check if a singly linked list is palindrome
return 0;
}
Java
class LinkedList
{
Node head; // head of list
Node slow_ptr, fast_ptr,second_half;
Node(char d)
{
data = d;
next = null;
}
579
Chapter 97. Function to check if a singly linked list is palindrome
// Now reverse the second half and compare it with first half
second_half = slow_ptr;
prev_of_slow_ptr.next = null; // NULL terminate first half
reverse(); // Reverse the second half
res = compareLists(head, second_half); // compare
if (midnode != null)
{
// If there was a mid node (odd size case) which
580
Chapter 97. Function to check if a singly linked list is palindrome
581
Chapter 97. Function to check if a singly linked list is palindrome
return false;
}
582
Chapter 97. Function to check if a singly linked list is palindrome
System.out.println("");
}
}
}
}
Output:
a->NULL
Palindrome
b->a->NULL
Not Palindrome
a->b->a->NULL
Is Palindrome
c->a->b->a->NULL
Not Palindrome
a->c->a->b->a->NULL
Not Palindrome
b->a->c->a->b->a->NULL
Not Palindrome
a->b->a->c->a->b->a->NULL
Is Palindrome
583
Chapter 97. Function to check if a singly linked list is palindrome
However, the trick in identifying double pointer. Passing single pointer is as good as pass-
by-value, and we will pass the same pointer again and again. We need to pass the address
of head pointer for reflecting the changes in parent recursive calls.
Thanks to Sharad Chandra for suggesting this approach.
C
return isp1;
}
584
Chapter 97. Function to check if a singly linked list is palindrome
return 0;
}
Java
585
Chapter 97. Function to check if a singly linked list is palindrome
class LinkedList
{
Node head; // head of list
Node left;
Node(char d)
{
data = d;
next = null;
}
}
return isp1;
}
586
Chapter 97. Function to check if a singly linked list is palindrome
return result;
}
587
Chapter 97. Function to check if a singly linked list is palindrome
System.out.println("Not Palindrome");
System.out.println("");
}
}
}
}
Output:
a->NULL
Not Palindrome
b->a->NULL
Not Palindrome
a->b->a->NULL
Is Palindrome
c->a->b->a->NULL
Not Palindrome
a->c->a->b->a->NULL
Not Palindrome
b->a->c->a->b->a->NULL
Not Palindrome
a->b->a->c->a->b->a->NULL
Is Palindrome
Source
https://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/
588
Chapter 98
new_node->data = malloc(data_size);
589
Chapter 98. Generic Linked List in C
new_node->next = (*head_ref);
590
Chapter 98. Generic Linked List in C
return 0;
}
Output:
This article is contributed by Himanshu Gupta. Please write comments if you find any-
thing incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/generic-linked-list-in-c-2/
591
Chapter 99
Input: (0,10)->(1,10)->(5,10)->(7,10)
|
(7,5)->(20,5)->(40,5)
Output: Linked List should be changed to following
(0,10)->(7,10)
|
(7,5)->(40,5)
The given linked list represents a horizontal line from (0,10)
to (7, 10) followed by a vertical line from (7, 10) to (7, 5),
followed by a horizontal line from (7, 5) to (40, 5).
Input: (2,3)->(4,3)->(6,3)->(10,3)->(12,3)
Output: Linked List should be changed to following
(2,3)->(12,3)
There is only one vertical line, so all middle points are removed.
592
Chapter 99. Given a linked list of line segments, remove middle points
C/C++
593
Chapter 99. Given a linked list of line segments, remove middle points
594
Chapter 99. Given a linked list of line segments, remove middle points
return head;
}
push(&head, 40,5);
push(&head, 20,5);
push(&head, 10,5);
push(&head, 10,8);
push(&head, 10,10);
push(&head, 3,10);
push(&head, 1,10);
push(&head, 0,10);
printf("Given Linked List: \n");
printList(head);
if (deleteMiddle(head) != NULL);
{
printf("Modified Linked List: \n");
printList(head);
}
return 0;
}
Java
595
Chapter 99. Given a linked list of line segments, remove middle points
// if horizontal
else if (head.y == Next.y)
{
// find middle nodes with same value as y and
// delete them
while (NextNext != null && Next.y == NextNext.y)
{
head.next = Next.next;
Next.next = null;
596
Chapter 99. Given a linked list of line segments, remove middle points
// restore head
head = temp;
void printList()
{
Node temp = head;
while (temp != null)
{
System.out.print("("+temp.x+","+temp.y+")->");
temp = temp.next;
}
System.out.println();
}
597
Chapter 99. Given a linked list of line segments, remove middle points
llist.push(40,5);
llist.push(20,5);
llist.push(10,5);
llist.push(10,8);
llist.push(10,10);
llist.push(3,10);
llist.push(1,10);
llist.push(0,10);
System.out.println("Given list");
llist.printList();
if (llist.deleteMiddle() != null)
{
System.out.println("Modified Linked List is");
llist.printList();
}
}
} /* This code is contributed by Rajat Mishra */
Python
598
Chapter 99. Given a linked list of line segments, remove middle points
Next = self.head.next
NextNext = Next.next
# check if this is vertical or horizontal line
if self.head.x == Next.x:
# Find middle nodes with same value as x and
# delete them.
while NextNext != None and Next.x == NextNext.x:
self.head.next = Next.next
Next.next = None
# Update NextNext for the next iteration
Next = NextNext
NextNext = NextNext.next
elif self.head.y == Next.y:
# find middle nodes with same value as y and
# delete them
while NextNext != None and Next.y == NextNext.y:
self.head.next = Next.next
Next.next = None
# Update NextNext for the next iteration
Next = NextNext
NextNext = NextNext.next
else:
# Adjacent points should have same x or same y
print "Given list is not valid"
return None
# recur for other segment
# temporarily store the head and move head forward.
temp = self.head
self.head = self.head.next
# call deleteMiddle() for next segment
self.deleteMiddle()
# restore head
self.head = temp
# return the head
return self.head
599
Chapter 99. Given a linked list of line segments, remove middle points
def printList(self):
temp = self.head
while temp != None:
print "(" + str(temp.x) + "," + str(temp.y) + ")->",
temp = temp.next
print ''
# Driver program
llist = LinkedList()
llist.push(40,5)
llist.push(20,5)
llist.push(10,5)
llist.push(10,8)
llist.push(10,10)
llist.push(3,10)
llist.push(1,10)
llist.push(0,10)
if llist.deleteMiddle() != None:
print "Modified Linked List is"
llist.printList()
Output:
Time Complexity of the above solution is O(n) where n is number of nodes in given linked
list.
Exercise:
The above code is recursive, write an iterative code for the same problem. Please see below
for solution.
Iterative approach for removing middle points in a linked list of line segements
This article is contributed by Sanket Jain. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/given-linked-list-line-segments-remove-middle-points/
600
Chapter 100
Given a linked list which is sorted, how will you insert in sorted way - GeeksforGeeks
Given a sorted linked list and a value to insert, write a function to insert the value in sorted
way.
Initial Linked List
Algorithm:
Let input linked list is sorted in increasing order.
601
Chapter 100. Given a linked list which is sorted, how will you insert in sorted way
Implementation:
C/C++
602
Chapter 100. Given a linked list which is sorted, how will you insert in sorted way
return new_node;
}
603
Chapter 100. Given a linked list which is sorted, how will you insert in sorted way
return 0;
}
Java
new_node.next = current.next;
current.next = new_node;
}
}
/*Utility functions*/
604
Chapter 100. Given a linked list which is sorted, how will you insert in sorted way
Python
# Node class
class Node:
605
Chapter 100. Given a linked list which is sorted, how will you insert in sorted way
self.next = None
class LinkedList:
else :
new_node.next = current.next
current.next = new_node
# Driver program
llist = LinkedList()
new_node = Node(5)
606
Chapter 100. Given a linked list which is sorted, how will you insert in sorted way
llist.sortedInsert(new_node)
new_node = Node(10)
llist.sortedInsert(new_node)
new_node = Node(7)
llist.sortedInsert(new_node)
new_node = Node(3)
llist.sortedInsert(new_node)
new_node = Node(1)
llist.sortedInsert(new_node)
new_node = Node(9)
llist.sortedInsert(new_node)
print "Create Linked List"
llist.printList()
Output:
current = &((*current)->next);
Source
https://www.geeksforgeeks.org/given-a-linked-list-which-is-sorted-how-will-you-insert-in-sorted-way/
607
Chapter 101
Given a linked list, reverse alternate nodes and append at the end - GeeksforGeeks
Given a linked list, reverse alternate nodes and append them to end of list. Extra allowed
space is O(1)
Examples
The idea is to maintain two linked lists, one list of all odd positioned nodes (1, 3, 5 in
above example) and other list of all even positioned nodes (6, 4 and 2 in above example).
Following are detailed steps.
1) Traverse the given linked list which is considered as odd list. Do following for every
visited node.
……a) If the node is even node, remove it from odd list and add it to the front of even node
list. Nodes are added at front to keep the reverse order.
2) Append the even node list at the end of odd node list.
C
#include<stdio.h>
#include<stdlib.h>
608
Chapter 101. Given a linked list, reverse alternate nodes and append at the end
/* Function to reverse all even positioned node and append at the end
odd is the head node of given linked list */
void rearrange(struct Node *odd)
{
// If linked list has less than 3 nodes, no change is required
if (odd == NULL || odd->next == NULL || odd->next->next == NULL)
return;
609
Chapter 101. Given a linked list, reverse alternate nodes and append at the end
rearrange(start);
return 0;
}
Java
610
Chapter 101. Given a linked list, reverse alternate nodes and append at the end
class LinkedList {
int data;
Node next;
Node(int item) {
data = item;
next = null;
}
}
/* Function to reverse all even positioned node and append at the end
odd is the head node of given linked list */
void rearrange(Node odd) {
611
Chapter 101. Given a linked list, reverse alternate nodes and append at the end
System.out.println("");
list.rearrange(head);
}
}
Python
612
Chapter 101. Given a linked list, reverse alternate nodes and append at the end
# Node Class
class Node:
def printList(self):
temp = self.head
while(temp):
print temp.data,
temp = temp.next
def rearrange(self):
613
Chapter 101. Given a linked list, reverse alternate nodes and append at the end
start.rearrange()
Output:
614
Chapter 101. Given a linked list, reverse alternate nodes and append at the end
Time Complexity: The above code simply traverses the given linked list. So time complexity
is O(n)
Auxiliary Space: O(1)
This article is contributed by Aman Gupta. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/given-linked-list-reverse-alternate-nodes-append-end/
615
Chapter 102
Given only a pointer to a node to be deleted in a singly linked list, how do you delete it? -
GeeksforGeeks
A simple solution is to traverse the linked list until you find the node you want to delete.
But this solution requires pointer to the head node which contradicts the problem statement.
Fast solution is to copy the data from the next node to the node to be deleted and delete
the next node. Something like following.
Program:
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
616
Chapter 102. Given only a pointer to a node to be deleted in a singly linked list, how do
you delete it?
int data;
struct Node* next;
};
617
Chapter 102. Given only a pointer to a node to be deleted in a singly linked list, how do
you delete it?
1->12->1->4->1 */
push(&head, 1);
push(&head, 4);
push(&head, 1);
push(&head, 12);
push(&head, 1);
Java
class LinkedList {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
618
Chapter 102. Given only a pointer to a node to be deleted in a singly linked list, how do
you delete it?
node.data = temp.data;
node.next = temp.next;
System.gc();
This solution doesn’t work if the node to be deleted is the last node of the
list. To make this solution work we can mark the end node as a dummy node. But the
programs/functions that are using this function should also be modified.
Try this problem for doubly linked list.
Source
https://www.geeksforgeeks.org/in-a-linked-list-given-only-a-pointer-to-a-node-to-be-deleted-in-a-singly-linked-list-
619
Chapter 103
Given only a pointer/reference to a node to be deleted in a singly linked list, how do you
delete it? - GeeksforGeeks
Given a pointer to a node to be deleted, delete the node. Note that we don’t have pointer
to head node.
A simple solution is to traverse the linked list until you find the node you want to delete.
But this solution requires pointer to the head node which contradicts the problem statement.
Fast solution is to copy the data from the next node to the node to be deleted and delete
the next node. Something like following.
620
Chapter 103. Given only a pointer/reference to a node to be deleted in a singly linked list,
how do you delete it?
Program:
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
621
Chapter 103. Given only a pointer/reference to a node to be deleted in a singly linked list,
how do you delete it?
node_ptr->next = temp->next;
free(temp);
}
Java
class LinkedList
{
Node head; // head of the list
class Node
{
int data;
Node next;
Node(int d) {data = d; next = null; }
}
622
Chapter 103. Given only a pointer/reference to a node to be deleted in a singly linked list,
how do you delete it?
System.out.println("Before deleting");
llist.printList();
623
Chapter 103. Given only a pointer/reference to a node to be deleted in a singly linked list,
how do you delete it?
System.out.println("\nAfter Deleting");
llist.printList();
}
}
// This code is contributed by Rajat Mishra
Output:
Before deleting
1 12 1 4 1
After deleting
12 1 4 1
This solution doesn’t work if the node to be deleted is the last node of the
list. To make this solution work we can mark the end node as a dummy node. But the
programs/functions that are using this function should also be modified.
Exercise: Try this problem for doubly linked list.
Source
https://www.geeksforgeeks.org/given-only-a-pointer-to-a-node-to-be-deleted-in-a-singly-linked-list-how-do-you-del
624
Chapter 104
1->2->3->4
If we are at 3 and there is a need to remove it, then 2 need to be linked with 4
and as from 3, 2 can’t be accessed as it is singly linked list. So, the list has to
be traversed again i.e O(n), but if we have doubly linked list i.e.
1234
625
Chapter 104. Hashtables Chaining with Doubly Linked Lists
// declaration of node
struct hash_node {
int val, key;
hash_node* next;
hash_node* prev;
};
// hashmap's declaration
class HashMap {
public:
hash_node **hashtable, **top;
// constructor
HashMap()
{
// create a empty hashtable
hashtable = new hash_node*[tablesize];
top = new hash_node*[tablesize];
for (int i = 0; i < tablesize; i++) {
hashtable[i] = NULL;
top[i] = NULL;
}
}
// destructor
~HashMap()
{
delete[] hashtable;
}
// searching method
void find(int key)
{
// Applying hashFunc to find
// index for given key
626
Chapter 104. Hashtables Chaining with Doubly Linked Lists
// removing an element
void remove(int key)
{
// Applying hashFunc to find
// index for given key
int hash_val = HashFunc(key);
hash_node* entry = hashtable[hash_val];
if (entry->key != key || entry == NULL) {
cout << "Couldn't find any element at this key "
<< key << endl;
return;
}
627
Chapter 104. Hashtables Chaining with Doubly Linked Lists
top[hash_val] = entry->prev;
top[hash_val]->next = NULL;
delete entry;
entry = top[hash_val];
}
}
entry = entry->next;
}
cout << "Element was successfully removed at the key "
<< key << endl;
}
// inserting method
void add(int key, int value)
{
// Applying hashFunc to find
// index for given key
int hash_val = HashFunc(key);
hash_node* entry = hashtable[hash_val];
628
Chapter 104. Hashtables Chaining with Doubly Linked Lists
cout << "Value " << value << " was successfully"
" added at key " << key << endl;
}
};
// Driver Code
int main()
{
HashMap hash;
hash.add(4, 5);
hash.find(4);
hash.remove(4);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/hashtables-chaining-with-doubly-linked-lists/
629
Chapter 105
How does Floyd’s slow and fast pointers approach work? - GeeksforGeeks
We have discussed Floyd’s fast and slow pointer algorithms in Detect loop in a linked list.
The algorithm is to start two pointers, slow and fast from head of linked list. We move slow
one node at a time and fast two nodes at a time. If there is a loop, then they will definitely
meet. This approach works because of the following facts.
1) When slow pointer enters the loop, the fast pointer must be inside the loop. Let fast
pointer be distance k from slow.
2) Now if consider movements of slow and fast pointers, we can notice that distance between
them (from slow to fast) increase by one after every iteration. After one iteration (of slow
= next of slow and fast = next of next of fast), distance between slow and fast becomes
k+1, after two iterations, k+2, and so on. When distance becomes n, they meet because
they are moving in a cycle of length n.
For example, we can see in below diagram, initial distance is 2. After one iteration, distance
becomes 3, after 2 iterations, it becomes 4. After 3 iterations, it becomes 5 which is
distance 0. And they meet.
630
Chapter 105. How does Floyd’s slow and fast pointers approach work?
Source
https://www.geeksforgeeks.org/how-does-floyds-slow-and-fast-pointers-approach-work/
631
Chapter 106
How to write C functions that modify head pointer of a Linked List? - GeeksforGeeks
Consider simple representation (without any dummy node) of Linked List. Functions that
operate on such Linked lists can be divided in two categories:
1) Functions that do not modify the head pointer: Examples of such functions
include, printing a linked list, updating data members of nodes like adding given a value to
all nodes, or some other operation which access/update data of nodes
It is generally easy to decide prototype of functions of this category. We can always pass head
pointer as an argument and traverse/update the list. For example, the following function
that adds x to data members of all nodes.
2) Functions that modify the head pointer: Examples include, inserting a node at the
beginning (head pointer is always modified in this function), inserting a node at the end
(head pointer is modified only when the first node is being inserted), deleting a given node
(head pointer is modified when the deleted node is first node). There may be different ways
to update the head pointer in these functions. Let us discuss these ways using following
simple problem:
632
Chapter 106. How to write C functions that modify head pointer of a Linked List?
“Given a linked list, write a function deleteFirst() that deletes the first node of a given linked
list. For example, if the list is 1->2->3->4, then it should be modified to 2->3->4”
Algorithm to solve the problem is a simple 3 step process: (a) Store the head pointer (b)
change the head pointer to point to next node (c) delete the previous head node.
Following are different ways to update head pointer in deleteFirst() so that the list is updated
everywhere.
2.1) Make head pointer global: We can make the head pointer global so that it can be
accessed and updated in our function. Following is C code that uses global head pointer.
633
Chapter 106. How to write C functions that modify head pointer of a Linked List?
{
// store the old value of head pointer
struct Node *temp = head;
return head;
}
2.3) Use Double Pointer: This approach follows the simple C rule: if you want to modify
local variable of one function inside another function, pass pointer to that variable. So we
can pass pointer to the head pointer to modify the head pointer in our deleteFirst() function.
634
Chapter 106. How to write C functions that modify head pointer of a Linked List?
Source
https://www.geeksforgeeks.org/how-to-write-functions-that-modify-the-head-pointer-of-a-linked-list/
635
Chapter 107
636
Chapter 107. Identical Linked Lists
637
Chapter 107. Identical Linked Lists
return 0;
}
Java
638
Chapter 107. Identical Linked Lists
llist1.push(1);
llist1.push(2);
llist1.push(3);
llist2.push(1);
llist2.push(2);
llist2.push(3);
if (llist1.areIdentical(llist2) == true)
System.out.println("Identical ");
else
System.out.println("Not identical ");
}
} /* This code is contributed by Rajat Mishra */
Output:
Identical
Method 2 (Recursive)
Recursive solution code is much cleaner than the iterative code. You probably wouldn’t
639
Chapter 107. Identical Linked Lists
want to use the recursive version for production code however, because it will use stack
space which is proportional to the length of the lists
C
Java
640
Chapter 107. Identical Linked Lists
otherwise false */
boolean areIdentical(LinkedList listb)
{
return areIdenticalRecur(this.head, listb.head);
}
Time Complexity: O(n) for both iterative and recursive versions. n is the length of the
smaller list among a and b.
Source
https://www.geeksforgeeks.org/identical-linked-lists/
641
Chapter 108
Operations on Deque :
642
Chapter 108. Implementation of Deque using doubly linked list
643
Chapter 108. Implementation of Deque using doubly linked list
4. ELSE
5. IF rear == NULL, then
6. front = rear = newNode
7. ELSE
8. newNode->prev = rear
9. rear->next = newNode
10. rear = newNode
1. IF front == NULL
2. print "Underflow"
3. ELSE
4. Initalize temp = front
5. front = front->next
6. IF front == NULL
7. rear = NULL
8. ELSE
9. front->prev = NULL
10 Deallocate space for temp
1. IF front == NULL
2. print "Underflow"
3. ELSE
4. Initalize temp = rear
5. rear = rear->prev
6. IF rear == NULL
7. front = NULL
8. ELSE
9. rear->next = NULL
10 Deallocate space for temp
644
Chapter 108. Implementation of Deque using doubly linked list
public:
Deque()
{
front = rear = NULL;
Size = 0;
}
// Operations on Deque
void insertFront(int data);
void insertRear(int data);
void deleteFront();
void deleteRear();
int getFront();
int getRear();
int size();
bool isEmpty();
void erase();
};
645
Chapter 108. Implementation of Deque using doubly linked list
646
Chapter 108. Implementation of Deque using doubly linked list
newNode->prev = rear;
rear->next = newNode;
rear = newNode;
}
Size++;
}
}
647
Chapter 108. Implementation of Deque using doubly linked list
else
{
Node* temp = rear;
rear = rear->prev;
648
Chapter 108. Implementation of Deque using doubly linked list
free(temp);
}
Size = 0;
}
dq.deleteRear();
cout << "After deleting rear element new rear"
<< " is: " << dq.getRear() << endl;
dq.deleteFront();
cout << "After deleting front element new "
<< "front is: " << dq.getFront() << endl;
return 0;
}
Output :
649
Chapter 108. Implementation of Deque using doubly linked list
Source
https://www.geeksforgeeks.org/implementation-deque-using-doubly-linked-list/
650
Chapter 109
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// creating a list
vector<int> list;
651
Chapter 109. Implementing Iterator pattern of a single Linked List
return 0;
}
Output
1 2 3
One of the beauty of cin and cout is that they don’t demand format specifiers to work with
the type of data. This combined with templates make the code much cleaner and readable.
Although I prefer naming method in C++ start with caps, this implementation follows STL
rules to mimic exact set of method calls, viz push_back, begin, end.
Here is our own implementation of LinkedList and its Iterator pattern:
public:
LinkedList<T>() noexcept
{
// caution: static members can't be
// initialized by initializer list
m_spRoot = nullptr;
}
652
Chapter 109. Implementing Iterator pattern of a single Linked List
{
return Iterator(m_spRoot);
}
void Traverse();
// Prefix ++ overload
Iterator& operator++()
{
if (m_pCurrentNode)
m_pCurrentNode = m_pCurrentNode->pNext;
return *this;
}
// Postfix ++ overload
Iterator operator++(int)
{
Iterator iterator = *this;
++*this;
return iterator;
}
653
Chapter 109. Implementing Iterator pattern of a single Linked List
int operator*()
{
return m_pCurrentNode->data;
}
private:
const Node* m_pCurrentNode;
};
private:
class Node
{
T data;
Node* pNext;
return pNewNode;
}
654
Chapter 109. Implementing Iterator pattern of a single Linked List
pCrawler->pNext = pTemp;
}
}
while (pCrawler)
{
cout << pCrawler->data << " ";
pCrawler = pCrawler->pNext;
}
//Driver program
int main()
{
LinkedList<int> list;
655
Chapter 109. Implementing Iterator pattern of a single Linked List
return 0;
}
Output:
Exercise:
The above implementation works well when we have one data. Extend this code to work
for set of data wrapped in a class.
Source
https://www.geeksforgeeks.org/implementing-iterator-pattern-of-a-single-linked-list/
656
Chapter 110
In Java, LinkedList can be represented as a class and a Node as a separate class. The
LinkedList class contains a reference of Node class type.
class LinkedList {
Node head; // head of list
In this article, insertion in the list is done at the end, that is the new node is added after
657
Chapter 110. Implementing a Linked List in Java using Class
the last node of the given Linked List. For example, if the given Linked List is 5->10->15-
>20->25 and 30 is to be inserted, then the Linked List becomes 5->10->15->20->25->30.
Since a Linked List is typically represented by the head pointer of it, it is required to traverse
the list till the last node and then change the next of last node to new node.
import java.io.*;
int data;
Node next;
// Constructor
Node(int d)
{
data = d;
next = null;
}
}
658
Chapter 110. Implementing a Linked List in Java using Class
{
// Create a new node with given data
Node new_node = new Node(data);
new_node.next = null;
System.out.print("LinkedList: ");
// Go to next node
currNode = currNode.next;
}
}
// Driver code
public static void main(String[] args)
{
/* Start with the empty list. */
LinkedList list = new LinkedList();
659
Chapter 110. Implementing a Linked List in Java using Class
//
// ******INSERTION******
//
Output:
LinkedList: 1 2 3 4 5 6 7 8
For traversal, below is a general purpose function printList() that prints any given list by
traversing the list from head node to the last.
import java.io.*;
int data;
Node next;
// Constructor
Node(int d)
{
660
Chapter 110. Implementing a Linked List in Java using Class
data = d;
next = null;
}
}
System.out.print("LinkedList: ");
// Go to next node
currNode = currNode.next;
}
661
Chapter 110. Implementing a Linked List in Java using Class
// **************MAIN METHOD**************
//
// ******INSERTION******
//
Output:
LinkedList: 1 2 3 4 5 6 7 8
662
Chapter 110. Implementing a Linked List in Java using Class
import java.io.*;
int data;
Node next;
// Constructor
Node(int d)
{
data = d;
next = null;
}
}
663
Chapter 110. Implementing a Linked List in Java using Class
System.out.print("LinkedList: ");
// Go to next node
currNode = currNode.next;
}
System.out.println();
}
664
Chapter 110. Implementing a Linked List in Java using Class
// **************DELETION BY KEY**************
//
// CASE 1:
// If head node itself holds the key to be deleted
//
// CASE 2:
// If the key is somewhere other than at head
//
665
Chapter 110. Implementing a Linked List in Java using Class
//
// CASE 3: The key is not present
//
// **************MAIN METHOD**************
//
// ******INSERTION******
//
//
// ******DELETION BY KEY******
//
666
Chapter 110. Implementing a Linked List in Java using Class
Output:
LinkedList: 1 2 3 4 5 6 7 8
1 found and deleted
LinkedList: 2 3 4 5 6 7 8
4 found and deleted
LinkedList: 2 3 5 6 7 8
10 not found
LinkedList: 2 3 5 6 7 8
667
Chapter 110. Implementing a Linked List in Java using Class
(b) Change the next of previous node to the next node of current node.
(c) Free the memory of replaced node.
• Case 3: The position is greater than the size of the list, i.e. position
not found in the list
(a) In this case, No operation needs to be done.
import java.io.*;
int data;
Node next;
// Constructor
Node(int d)
{
data = d;
next = null;
}
}
668
Chapter 110. Implementing a Linked List in Java using Class
System.out.print("LinkedList: ");
// Go to next node
currNode = currNode.next;
}
System.out.println();
}
669
Chapter 110. Implementing a Linked List in Java using Class
{
// Store head node
Node currNode = list.head, prev = null;
//
// CASE 1:
// If index is 0, then head node itself is to be deleted
//
// CASE 2:
// If the index is greater than 0 but less than the size of LinkedList
//
// The counter
int counter = 0;
if (counter == index) {
// Since the currNode is the required position
// Unlink currNode from linked list
prev.next = currNode.next;
670
Chapter 110. Implementing a Linked List in Java using Class
// **************MAIN METHOD**************
//
// ******INSERTION******
//
//
// ******DELETION AT POSITION******
//
671
Chapter 110. Implementing a Linked List in Java using Class
Output:
LinkedList: 1 2 3 4 5 6 7 8
0 position element deleted
LinkedList: 2 3 4 5 6 7 8
2 position element deleted
LinkedList: 2 3 5 6 7 8
10 position element not found
LinkedList: 2 3 5 6 7 8
import java.io.*;
int data;
Node next;
672
Chapter 110. Implementing a Linked List in Java using Class
// Constructor
Node(int d)
{
data = d;
next = null;
}
}
// **************INSERTION**************
// **************TRAVERSAL**************
System.out.print("\nLinkedList: ");
673
Chapter 110. Implementing a Linked List in Java using Class
// Go to next node
currNode = currNode.next;
}
System.out.println("\n");
}
// **************DELETION BY KEY**************
//
// CASE 1:
// If head node itself holds the key to be deleted
//
// CASE 2:
// If the key is somewhere other than at head
//
674
Chapter 110. Implementing a Linked List in Java using Class
//
// CASE 3: The key is not present
//
// **************DELETION AT A POSITION**************
//
// CASE 1:
// If index is 0, then head node itself is to be deleted
675
Chapter 110. Implementing a Linked List in Java using Class
//
// CASE 2:
// If the index is greater than 0 but less than the size of LinkedList
//
// The counter
int counter = 0;
if (counter == index) {
// Since the currNode is the required position
// Unlink currNode from linked list
prev.next = currNode.next;
// **************MAIN METHOD**************
676
Chapter 110. Implementing a Linked List in Java using Class
//
// ******INSERTION******
//
//
// ******DELETION BY KEY******
//
//
677
Chapter 110. Implementing a Linked List in Java using Class
// ******DELETION AT POSITION******
//
Output:
LinkedList: 1 2 3 4 5 6 7 8
LinkedList: 2 3 4 5 6 7 8
LinkedList: 2 3 5 6 7 8
10 not found
LinkedList: 2 3 5 6 7 8
LinkedList: 3 5 6 7 8
678
Chapter 110. Implementing a Linked List in Java using Class
LinkedList: 3 5 7 8
LinkedList: 3 5 7 8
Source
https://www.geeksforgeeks.org/implementing-a-linked-list-in-java-using-class/
679
Chapter 111
In-place Merge two linked lists without changing links of first list - GeeksforGeeks
Given two sorted singly linked lists having n and m elements each, merge them using constant
space. First n smallest elements in both the lists should become part of first list and rest
elements should be part of second list. Sorted order should be maintained. We are not
allowed to change pointers of first linked list.
For example,
Input:
First List: 2->4->7->8->10
Second List: 1->3->12
Output:
First List: 1->2->3->4->7
Second List: 8->10->12
We strongly recommend you to minimize your browser and try this yourself
first.
The problem becomes very simple if we’re allowed to change pointers of first linked list. If we
are allowed to change links, we can simply do something like merge of merge-sort algorithm.
We assign first n smallest elements to the first linked list where n is the number of elements
in first linked list and the rest to second linked list. We can achieve this in O(m + n) time
and O(1) space, but this solution violates the requirement that we can’t change links of first
list.
680
Chapter 111. In-place Merge two linked lists without changing links of first list
The problem becomes a little tricky as we’re not allowed to change pointers in first linked
list. The idea is something similar to this post but as we are given singly linked list, we
can’t proceed backwards with the last element of LL2.
The idea is for each element of LL1, we compare it with first element of LL2. If LL1 has
a greater element than first element of LL2, then we swap the two elements involved. To
keep LL2 sorted, we need to place first element of LL2 at its correct position. We can find
mismatch by traversing LL2 once and correcting the pointers.
Below is C++ implementation of this idea.
681
Chapter 111. In-place Merge two linked lists without changing links of first list
{
// for each element of LL1,
// compare it with first element of LL2.
if (a->data > b->data)
{
// swap the two elements involved
// if LL1 has a greater element
swap(a->data, b->data);
682
Chapter 111. In-place Merge two linked lists without changing links of first list
// Driver code
int main()
{
struct Node *a = NULL;
push(&a, 10);
push(&a, 8);
push(&a, 7);
push(&a, 4);
push(&a, 2);
mergeLists(a, b);
return 0;
}
Output :
Source
https://www.geeksforgeeks.org/in-place-merge-two-linked-list-without-changing-links-of-first-list/
683
Chapter 112
684
Chapter 112. In-place conversion of Sorted DLL to Balanced BST
The Doubly Linked List conversion is very much similar to this Singly Linked List problem
and the method 1 is exactly same as the method 1 ofprevious post. Method 2 is also almost
same. The only difference in method 2 is, instead of allocating new nodes for BST, we reuse
same DLL nodes. We use prev pointer as left and next pointer as right.
Method 1 (Simple)
Following is a simple algorithm where we first find the middle node of list and make it root
of the tree to be constructed.
C++
#include<stdio.h>
#include<stdlib.h>
/* A Doubly Linked List node that will also be used as a tree node */
685
Chapter 112. In-place conversion of Sorted DLL to Balanced BST
struct Node
{
int data;
/* This function counts the number of nodes in Linked List and then calls
sortedListToBSTRecur() to construct BST */
struct Node* sortedListToBST(struct Node *head)
{
/*Count the number of nodes in Linked List */
int n = countNodes(head);
/* Construct BST */
return sortedListToBSTRecur(&head, n);
}
/* The main function that constructs balanced BST and returns root of it.
head_ref --> Pointer to pointer to head node of Doubly linked list
n --> No. of nodes in the Doubly Linked List */
struct Node* sortedListToBSTRecur(struct Node **head_ref, int n)
{
/* Base Case */
if (n <= 0)
return NULL;
/* head_ref now refers to middle node, make middle node as root of BST*/
struct Node *root = *head_ref;
686
Chapter 112. In-place conversion of Sorted DLL to Balanced BST
return root;
}
/* UTILITY FUNCTIONS */
/* A utility function that returns count of nodes in a given Linked List */
int countNodes(struct Node *head)
{
int count = 0;
struct Node *temp = head;
while(temp)
{
temp = temp->next;
count++;
}
return count;
}
687
Chapter 112. In-place conversion of Sorted DLL to Balanced BST
return 0;
}
Java
688
Chapter 112. In-place conversion of Sorted DLL to Balanced BST
class Node
{
int data;
Node next, prev;
Node(int d)
{
data = d;
next = prev = null;
}
}
class LinkedList
{
Node head;
/* Construct BST */
return sortedListToBSTRecur(n);
}
689
Chapter 112. In-place conversion of Sorted DLL to Balanced BST
head = head.next;
return root;
}
/* UTILITY FUNCTIONS */
/* A utility function that returns count of nodes in a
given Linked List */
int countNodes(Node head)
{
int count = 0;
Node temp = head;
while (temp != null)
{
temp = temp.next;
count++;
}
return count;
}
690
Chapter 112. In-place conversion of Sorted DLL to Balanced BST
void printList()
{
Node node = head;
while (node != null)
{
System.out.print(node.data + " ");
node = node.next;
}
}
Output:
691
Chapter 112. In-place conversion of Sorted DLL to Balanced BST
Source
https://www.geeksforgeeks.org/in-place-conversion-of-sorted-dll-to-balanced-bst/
692
Chapter 113
Insert a node after the n-th node from the end - GeeksforGeeks
Insert a node x after the nth node from the end in the given singly linked list. It is
guaranteed that the list contains the nth node from the end. Also 1 <= n.
Examples:
// structure of a node
struct Node {
693
Chapter 113. Insert a node after the n-th node from the end
int data;
Node* next;
};
694
Chapter 113. Insert a node after the n-th node from the end
int n = 4, x = 2;
insertAfterNthNode(head, n, x);
return 0;
}
Output:
695
Chapter 113. Insert a node after the n-th node from the end
// structure of a node
struct Node {
int data;
Node* next;
};
696
Chapter 113. Insert a node after the n-th node from the end
fast_ptr = fast_ptr->next;
}
int n = 4, x = 2;
insertAfterNthNode(head, n, x);
return 0;
}
Output:
697
Chapter 113. Insert a node after the n-th node from the end
Source
https://www.geeksforgeeks.org/insert-node-n-th-node-end/
698
Chapter 114
699
Chapter 114. Insert a node at a specific position in a linked list
if (pos == 0) {
700
Chapter 114. Insert a node at a specific position in a linked list
// Driver Code
int main()
{
// Creating the list 3->5->8->10
Node* head = NULL;
head = getNode(3);
head->next = getNode(5);
head->next->next = getNode(8);
head->next->next->next = getNode(10);
size = 4;
701
Chapter 114. Insert a node at a specific position in a linked list
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/insert-a-node-at-a-specific-position-in-a-linked-list/
702
Chapter 115
Input : a : 1->2->3->4->5->NULL
b : 7->8->9->10->11->NULL
k = 2
Output :1->2->7->8->9->10->11->3->4->5->NULL
Input : a: 10->15->20->NULL
b: 11->17->16->18->NULL
k = 3
Output : 10->15->20->11->17->16->18->NULL
703
Chapter 115. Insert a whole linked list into other at k-th position
704
Chapter 115. Insert a whole linked list into other at k-th position
705
Chapter 115. Insert a whole linked list into other at k-th position
{
if (head == NULL)
return;
printList(a);
cout << "\n";
706
Chapter 115. Insert a whole linked list into other at k-th position
printList(b);
insert(a, b, k);
return 0;
}
Output:
1 2 3 4 5
7 8 9 10 11
Resulting linked list 1 2 7 8 9 10 11 3 4 5
Source
https://www.geeksforgeeks.org/insert-whole-linked-list-k-th-position/
707
Chapter 116
C++
708
Chapter 116. Insert node into the middle of the linked list
// structure of a node
struct Node {
int data;
Node* next;
};
709
Chapter 116. Insert node into the middle of the linked list
int x = 3;
insertAtMid(&head, x);
return 0;
}
Java
710
Chapter 116. Insert node into the middle of the linked list
import java.io.*;
class LinkedList
{
static Node head; // head of list
/* Node Class */
static class Node {
int data;
Node next;
711
Chapter 116. Insert node into the middle of the linked list
ptr = ptr.next;
int x = 3;
insertAtMid(x);
Output:
712
Chapter 116. Insert node into the middle of the linked list
// structure of a node
struct Node {
int data;
Node* next;
};
else {
// get a new node
Node* newNode = getNode(x);
713
Chapter 116. Insert node into the middle of the linked list
int x = 3;
insertAtMid(&head, x);
714
Chapter 116. Insert node into the middle of the linked list
return 0;
}
Java
class LinkedList
{
static Node head; // head of list
/* Node Class */
static class Node {
int data;
Node next;
else {
// get a new node
Node newNode = new Node(x);
715
Chapter 116. Insert node into the middle of the linked list
int x = 3;
insertAtMid(x);
716
Chapter 116. Insert node into the middle of the linked list
Output:
Source
https://www.geeksforgeeks.org/insert-node-middle-linked-list/
717
Chapter 117
Algorithm:
Let input doubly linked list is sorted in increasing order.
New node passed to the function contains data in the data part and previous and next link
are set to NULL.
sortedInsert(head_ref, newNode)
if (head_ref == NULL)
head_ref = newNode
718
Chapter 117. Insert value in sorted way in a sorted doubly linked list
head_ref = newNode
else
Initialize current = head_ref
while (current->next != NULL and
current->next->data data)
current = current->next
newNode->next = current->next
if current->next != NULL
newNode->next->prev = newNode
current->next = newNode
newNode->prev = current
// if list is empty
719
Chapter 117. Insert value in sorted way in a sorted doubly linked list
if (*head_ref == NULL)
*head_ref = newNode;
else {
current = *head_ref;
current->next = newNode;
newNode->prev = current;
}
}
720
Chapter 117. Insert value in sorted way in a sorted doubly linked list
Output:
Source
https://www.geeksforgeeks.org/insert-value-sorted-way-sorted-doubly-linked-list/
721
Chapter 118
The main step is (2.a) which has been covered in below post.
Sorted Insert for Singly Linked List
Below is implementation of above algorithm
C++
722
Chapter 118. Insertion Sort for Singly Linked List
// Update current
current = next;
}
723
Chapter 118. Insertion Sort for Singly Linked List
new_node->next = current->next;
current->next = new_node;
}
}
724
Chapter 118. Insertion Sort for Singly Linked List
insertionSort(&a);
return 0;
}
Java
class node
{
int val;
node next;
725
Chapter 118. Insertion Sort for Singly Linked List
{
// Store next for next iteration
node next = current.next;
// insert current in sorted linked list
sortedInsert(current);
// Update current
current = next;
}
// Update head_ref to point to sorted linked list
head = sorted;
}
/*
* function to insert a new_node in a list. Note that
* this function expects a pointer to head_ref as this
* can modify the head of the input linked list
* (similar to push())
*/
void sortedInsert(node newnode)
{
/* Special case for the head end */
if (sorted == null || sorted.val >= newnode.val)
{
newnode.next = sorted;
sorted = newnode;
}
else
{
node current = sorted;
/* Locate the node before the point of insertion */
while (current.next != null && current.next.val < newnode.val)
{
current = current.next;
}
newnode.next = current.next;
current.next = newnode;
}
}
726
Chapter 118. Insertion Sort for Singly Linked List
Source
https://www.geeksforgeeks.org/insertion-sort-for-singly-linked-list/
727
Chapter 119
Given the start pointer pointing to the start of a Circular Doubly Linked List, an element
and a position. The task is to insert the element at the specified position in the given
Circular Doubly Linked List.
728
Chapter 119. Insertion at Specific Position in a Circular Doubly Linked List
The idea is to count the total number of elements in the list. Check whether the specified
location is valid or not, i.e. location is within the count.
If location is valid:
#include <iostream>
using namespace std;
729
Chapter 119. Insertion at Specific Position in a Circular Doubly Linked List
while (temp->next != t) {
cout << temp->data << " ";
temp = temp->next;
}
return 1;
}
}
730
Chapter 119. Insertion at Specific Position in a Circular Doubly Linked List
// counter at last
count++;
return count;
}
else {
// Assign the data
newNode->data = data;
731
Chapter 119. Insertion at Specific Position in a Circular Doubly Linked List
return true;
}
return false;
}
// If it is first element
// Put that node prev and next as start
// as it is circular
if (i == 0) {
*start = newNode;
newNode->prev = *start;
newNode->next = *start;
}
else {
// Find the last node
temp = (*start)->prev;
// Driver Code
732
Chapter 119. Insertion at Specific Position in a Circular Doubly Linked List
int main()
{
// Array elements to create
// circular doubly linked list
int arr[] = { 1, 2, 3, 4, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
// Start Pointer
struct node* start = NULL;
return 0;
}
Output:
Time Complexity: O(n) => for counting the list, O(n) => Inserting the elements. So,
total complexity is O(n + n) = O(n)
Source
https://www.geeksforgeeks.org/insertion-at-specific-position-in-a-circular-doubly-linked-list/
733
Chapter 120
Input : 72 76 80 94 90 70
capacity = 3
Output : Unrolled Linked List :
72 76
80 94
90 70
Explanation : The working is well shown in the
algorithm below. The nodes get broken at the
mentioned capacity i.e., 3 here, when 3rd element
is entered, the flow moves to another newly created
node. Every node contains an array of size
(int)[(capacity / 2) + 1]. Here it is 2.
734
Chapter 120. Insertion in Unrolled Linked List
Input : 49 47 62 51 77 17 71 71 35 76 36 54
capacity = 5
Output :
Unrolled Linked List :
49 47 62
51 77 17
71 71 35
76 36 54
Explanation : The working is well shown in the
algorithm below. The nodes get broken at the
mentioned capacity i.e., 5 here, when 5th element
is entered, the flow moves to another newly
created node. Every node contains an array of
size (int)[(capacity / 2) + 1]. Here it is 3.
Algorithm :
Insert (ElementToBeInserted)
if start_pos == NULL
Insert the first element into the first node
start_pos.numElement ++
end_pos = start_pos
If end_pos.numElements + 1 < node_size
end_pos.numElements.push(newElement)
end_pos.numElements ++
else
create a new Node new_node
move final half of end_pos.data into new_node.data
new_node.data.push(newElement)
end_pos.numElements = end_pos.data.size / 2 + 1
end_pos.next = new_node
end_pos = new_node
Following is the Java implementation of the insertion and display operation. In the below
code, the capacity is 5 and random numbers are input.
Java
735
Chapter 120. Insertion in Unrolled Linked List
int num_elements;
int array[];
// Constructor
public UnrollNode(int n)
{
next = null;
num_elements = 0;
array = new int[n];
}
}
int size_node;
int nNode;
// Parameterized Constructor
UnrollLinkList(int capacity)
{
start_pos = null;
end_pos = null;
nNode = 0;
size_node = capacity + 1;
}
// Insertion operation
void Insert(int num)
{
nNode++;
736
Chapter 120. Insertion in Unrolled Linked List
node_pointer.array[j++] = num;
node_pointer.num_elements = j;
end_pos.num_elements = end_pos.num_elements / 2 + 1;
end_pos.next = node_pointer;
end_pos = node_pointer;
}
}
/* Main Class */
class UnrolledLinkedList_Check {
// Driver code
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
737
Chapter 120. Insertion in Unrolled Linked List
Output:
Entered Element is 90
Entered Element is 3
Entered Element is 12
Entered Element is 43
Entered Element is 88
Entered Element is 94
Entered Element is 15
738
Chapter 120. Insertion in Unrolled Linked List
90 3 12
43 88 94 15
Entered Element is 7
Entered Element is 67
Entered Element is 74
Entered Element is 85
Entered Element is 48
739
Chapter 120. Insertion in Unrolled Linked List
Source
https://www.geeksforgeeks.org/insertion-unrolled-linked-list/
740
Chapter 121
#include<stdio.h>
#include<stdlib.h>
/*This solution uses the temporary dummy to build up the result list */
struct Node* sortedIntersect(struct Node* a, struct Node* b)
741
Chapter 121. Intersection of two Sorted Linked Lists
{
struct Node dummy;
struct Node* tail = &dummy;
dummy.next = NULL;
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging of the linked list */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
742
Chapter 121. Intersection of two Sorted Linked Lists
}
}
/* Let us create the first sorted linked list to test the functions
Created linked list will be 1->2->3->4->5->6 */
push(&a, 6);
push(&a, 5);
push(&a, 4);
push(&a, 3);
push(&a, 2);
push(&a, 1);
getchar();
}
Time Complexity: O(m+n) where m and n are number of nodes in first and second linked
lists respectively.
Method 2 (Using Local References)
This solution is structurally very similar to the above, but it avoids using a dummy node
Instead, it maintains a struct node** pointer, lastPtrRef, that always points to the last
pointer of the result list. This solves the same case that the dummy node did — dealing
with the result list when it is empty. If you are trying to build up a list at its tail, either
the dummy node or the struct node** “reference” strategy can be used
#include<stdio.h>
#include<stdlib.h>
743
Chapter 121. Intersection of two Sorted Linked Lists
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging of the linked list */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
744
Chapter 121. Intersection of two Sorted Linked Lists
new_node->next = (*head_ref);
/* Let us create the first sorted linked list to test the functions
Created linked list will be 1->2->3->4->5->6 */
push(&a, 6);
push(&a, 5);
push(&a, 4);
push(&a, 3);
push(&a, 2);
push(&a, 1);
getchar();
}
745
Chapter 121. Intersection of two Sorted Linked Lists
Time Complexity: O(m+n) where m and n are number of nodes in first and second linked
lists respectively.
Method 3 (Recursive)
Below is the recursive implementation of sortedIntersect().
#include<stdio.h>
#include<stdlib.h>
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging of the linked list */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
746
Chapter 121. Intersection of two Sorted Linked Lists
/* Let us create the first sorted linked list to test the functions
Created linked list will be 1->2->3->4->5->6 */
push(&a, 6);
push(&a, 5);
push(&a, 4);
push(&a, 3);
push(&a, 2);
push(&a, 1);
747
Chapter 121. Intersection of two Sorted Linked Lists
return 0;
}
Time Complexity: O(m+n) where m and n are number of nodes in first and second linked
lists respectively.
References:
cslibrary.stanford.edu/105/LinkedListProblems.pdf
Source
https://www.geeksforgeeks.org/intersection-of-two-sorted-linked-lists/
748
Chapter 122
Iterative approach for removing middle points in a linked list of line segements - Geeks-
forGeeks
This post explains the iterative approach of this problem.
We maintain two pointers, prev and temp. If these two have either x or y same, we move
forward till the equality holds and keep deleting the nodes in between. The node from which
the equality started, we adjust the next pointer of that node.
749
Chapter 122. Iterative approach for removing middle points in a linked list of line
segements
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
while (temp) {
750
Chapter 122. Iterative approach for removing middle points in a linked list of line
segements
push(&head, 40,5);
push(&head, 20,5);
push(&head, 10,5);
push(&head, 10,8);
push(&head, 10,10);
push(&head, 3,10);
push(&head, 1,10);
push(&head, 0,10);
delete_Middle_Nodes(head);
return 0;
}
Output:
751
Chapter 122. Iterative approach for removing middle points in a linked list of line
segements
Source
https://www.geeksforgeeks.org/iterative-approach-for-removing-middle-points-in-a-linked-list-of-line-segements/
752
Chapter 123
Iteratively Reverse a linked list using only 2 pointers (An Interesting Method) - Geeks-
forGeeks
Given pointer to the head node of a linked list, the task is to reverse the linked list.
Examples:
We have seen how to reverse a linked list in article Reverse a linked list. In iterative
method we had used 3 pointers prev, cur and next. Below is an interesting approach
that uses only two pointers. The idea is to use XOR to swap pointers.
C/C++
753
Chapter 123. Iteratively Reverse a linked list using only 2 pointers (An Interesting Method)
*head_ref = prev;
}
754
Chapter 123. Iteratively Reverse a linked list using only 2 pointers (An Interesting Method)
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 85);
Python
# Iteratively Reverse a linked list using only 2 pointers (An Interesting Method)
# Python program to reverse a linked list
# Link list node
# node class
class node:
class LinkedList:
755
Chapter 123. Iteratively Reverse a linked list using only 2 pointers (An Interesting Method)
756
Chapter 123. Iteratively Reverse a linked list using only 2 pointers (An Interesting Method)
llist.reverse()
print "\nReversed Linked List"
llist.printList()
Output:
Alternate Solution :
757
Chapter 123. Iteratively Reverse a linked list using only 2 pointers (An Interesting Method)
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 85);
Output:
Source
https://www.geeksforgeeks.org/iteratively-reverse-a-linked-list-using-only-2-pointers/
758
Chapter 124
Input : NULL
Output : NULL
Input : 1->NULL
Output : 1->NULL
Iterative Method
Source
https://www.geeksforgeeks.org/java-program-for-reverse-a-linked-list/
759
Chapter 124. Java Program for Reverse a linked list
Java
class LinkedList {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
760
Chapter 124. Java Program for Reverse a linked list
Recursive Method:
/* empty list */
if (*head_ref == NULL)
return;
/* reverse the rest list and put the first element at the end */
recursiveReverse(&rest);
first->next->next = first;
Java
761
Chapter 124. Java Program for Reverse a linked list
class LinkedList {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
reverseUtil(next1, curr);
return head;
}
762
Chapter 124. Java Program for Reverse a linked list
Please refer complete article on Reverse a linked list for more details!
763
Chapter 125
Input : n = 5
m = 3
Output : 4
We have discussed different solutions of this problem (here and here). In this post a simple
circular linked list based solution is discussed.
1) Create a circular linked list of size n.
2) Traverse through linked list and one by one delete every m-th node until there is one
node left.
3) Return value of the only left node.
C++
764
Chapter 125. Josephus Circle using circular linked list
765
Chapter 125. Josephus Circle using circular linked list
ptr1 = ptr1->next;
count++;
}
Java
766
Chapter 125. Josephus Circle using circular linked list
{
prev.next = new Node(i);
prev = prev.next;
}
while(ptr1.next != ptr1)
{
Output :
767
Chapter 125. Josephus Circle using circular linked list
Source
https://www.geeksforgeeks.org/josephus-circle-using-circular-linked-list/
768
Chapter 126
Input :
m : 123456789123456789123456789123456789123456789123456789
n : 456789123456789123456789123456789123456789123456789
Output :
Product : 563937184884934839205932493526930147847927802168925...
30351019811918920046486820281054720515622620750190521
Sum : 123913578246913578246913578246913578246913578246913578
Difference : 123000000000000000000000000000000000000000000000000000
Quotient : 270
Remainder(%) : 123725790123725790123725790123725790123725790123759
Input :
m : 55
n : 2
Output :
Product : 110
Sum : 57
Difference : 53
Quotient : 27
Remainder(%) : 1
769
Chapter 126. Large number arithmetic using doubly linked list
Approach : Split the number into digits in a doubly linked list. Using basic addition prin-
ciples that goes digit by digit, with a carry are implemented in add and subtract functions.
These functions are now used to carry out multiplication and division operations using the
basic approach of multiplying last digit to all and then shifting and adding or finding the
closest large multiple to divisor to divide the dividend. Finally the results are displayed
using the display function.
Below is the implementation of above approach :
class HugeInt {
public:
HugeInt();
~HugeInt();
int length();
void add(HugeInt*, HugeInt*);
770
Chapter 126. Large number arithmetic using doubly linked list
if (head == NULL)
head = tail = temp;
else {
head->prev = temp;
temp->next = head;
head = temp;
}
size++;
}
if (tail == NULL)
head = tail = temp;
else {
tail->next = temp;
temp->prev = tail;
tail = temp;
}
size++;
}
/*
To display the number can be
771
Chapter 126. Large number arithmetic using doubly linked list
/*
Uses simple addition method that we
follow using carry*/
void HugeInt::add(HugeInt* a, HugeInt* b)
{
int c = 0, s;
HugeInt* a1 = new HugeInt(*a);
HugeInt* b1 = new HugeInt(*b);
772
Chapter 126. Large number arithmetic using doubly linked list
this->head = NULL;
this->tail = NULL;
this->size = 0;
773
Chapter 126. Large number arithmetic using doubly linked list
a1->tail = a1->tail->prev;
}
insertInFront(s);
}
}
774
Chapter 126. Large number arithmetic using doubly linked list
pr->mul(b2, mp);
if (!cmp(ex, pr))
break;
mp->head = mp->tail = NULL;
pr->head = pr->tail = NULL;
mp->size = pr->size = 0;
}
mp->insertInEnd(i - 1);
pr->mul(b1, mp);
ex->dif(ex, pr);
insertInEnd(i - 1);
mp->head = mp->tail = NULL;
pr->head = pr->tail = NULL;
mp->size = pr->size = 0;
mp->insertInEnd(i - 1);
pr->mul(b1, mp);
ex->dif(ex, pr);
insertInEnd(i - 1);
775
Chapter 126. Large number arithmetic using doubly linked list
a1->head = a1->head->next;
}
add(this, pro);
k++;
b->tail = b->tail->prev;
pro->head = pro->tail = NULL;
pro->size = 0;
}
}
776
Chapter 126. Large number arithmetic using doubly linked list
class HugeIntLL
{
public:
HugeIntLL();
~HugeIntLL();
int length();
void add(HugeIntLL*, HugeIntLL*);
void mul(HugeIntLL*, HugeIntLL*);
void dif(HugeIntLL*, HugeIntLL*);
void quo(HugeIntLL*, HugeIntLL*);
int cmp(HugeIntLL*, HugeIntLL*);
Node* head;
Node* tail;
int size;
};
777
Chapter 126. Large number arithmetic using doubly linked list
if (head == NULL)
head = tail = temp;
else
{
head->prev = temp;
temp->next = head;
head = temp;
}
size++;
}
if (tail == NULL)
head = tail = temp;
else
{
tail->next = temp;
temp->prev = tail;
tail = temp;
}
size++;
}
/*
To display the number can be
modified to remove leading zeros*/
void HugeIntLL::display()
{
Node* temp = head;
778
Chapter 126. Large number arithmetic using doubly linked list
int HugeIntLL::length()
{
return size;
}
779
Chapter 126. Large number arithmetic using doubly linked list
this->head = NULL;
this->tail = NULL;
this->size = 0;
780
Chapter 126. Large number arithmetic using doubly linked list
}
insertInFront(s);
}
}
781
Chapter 126. Large number arithmetic using doubly linked list
mp->insertInEnd(i - 1);
pr->mul(b1, mp);
ex->dif(ex, pr);
insertInEnd(i - 1);
mp->head = mp->tail = NULL;
pr->head = pr->tail = NULL;
mp->size = pr->size = 0;
mp->insertInEnd(i - 1);
pr->mul(b1, mp);
782
Chapter 126. Large number arithmetic using doubly linked list
ex->dif(ex, pr);
insertInEnd(i - 1);
a1->head = a1->head->next;
}
add(this, pro);
k++;
b->tail = b->tail->prev;
pro->head = pro->tail = NULL;
pro->size = 0;
}
}
// Driver code
783
Chapter 126. Large number arithmetic using doubly linked list
int main()
{
HugeIntLL* m = new HugeIntLL();
HugeIntLL* n = new HugeIntLL();
HugeIntLL* s = new HugeIntLL();
HugeIntLL* p = new HugeIntLL();
HugeIntLL* d = new HugeIntLL();
HugeIntLL* q = new HugeIntLL();
string s1 = "12345678912345678912345678"
"9123456789123456789123456789";
string s2 = "45678913456789123456789123456"
"789123456789123456789";
d->dif(m2, n2);
d->display();
q->quo(m3, n3);
cout << endl;
784
Chapter 126. Large number arithmetic using doubly linked list
Output:
Product :
5639371848849348392059324935269301478479278021689253035101981191892004648682028105472051562262075
Sum :
123913578246913578246913578246913578246913578246913578
Difference (m-n) : m>n:
123000000000000000000000000000000000000000000000000000
Modulus :
000123725790123725790123725790123725790123725790123759
Quotient :
0270
Source
https://www.geeksforgeeks.org/large-number-arithmetic-using-doubly-linked-list/
785
Chapter 127
Length of longest palindrome list in a linked list using O(1) extra space - GeeksforGeeks
Given a linked list, find length of the longest palindrome list that exist in that linked list.
Examples:
A simple solution could be to copy linked list content to array and then find longest palin-
dromic subarray in array, but this solution is not allowed as it requires extra space.
The idea is based on iterative linked list reverse process. We iterate through given linked list
and one by one reverse every prefix of linked list from left. After reversing a prefix, we find
the longest common list beginning from reversed prefix and list after the reversed prefix.
Below is C++ implementation of above idea.
786
Chapter 127. Length of longest palindrome list in a linked list using O(1) extra space
return count;
}
787
Chapter 127. Length of longest palindrome list in a linked list using O(1) extra space
Output :
788
Chapter 127. Length of longest palindrome list in a linked list using O(1) extra space
Source
https://www.geeksforgeeks.org/length-longest-palindrome-list-linked-list-using-o1-extra-space/
789
Chapter 128
Method(Brute force)
Iteratively check if their exist any pair or not
C++
790
Chapter 128. Linked List Pair Sum
q = p->next;
while (q != NULL) {
p = p->next;
}
return 0;
}
791
Chapter 128. Linked List Pair Sum
return 0;
}
Output:
14 12
Time complexity:O(n*n)
Method 2 (using hashing)
1. Take a hashtable and mark all element with zero
2. Iteratively mark all the element as 1 in hashtable which are present in linked list
3. Iteratively find sum-current element of linked list is present in hashtable or not
C++
792
Chapter 128. Linked List Pair Sum
of the list. */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));
return false;
}
793
Chapter 128. Linked List Pair Sum
push(&head, 1);
push(&head, 18);
push(&head, 47);
push(&head, 16);
push(&head, 12);
push(&head, 14);
return 0;
}
Output:
14 12
Source
https://www.geeksforgeeks.org/linked-list-pair-sum/
794
Chapter 129
Input : 1->2->3->0->5->4->0->3->2->0
Output : 6->9->5
Input : 1->2->3->4
Output : 1->2->3->4
795
Chapter 129. Linked List Sum of Nodes Between 0s
// If we encounters 0, we need
// to update next pointers
else {
res.data = sum;
res.next = temp.next;
temp = res.next;
res = res.next;
sum = 0;
}
}
printList(head);
}
796
Chapter 129. Linked List Sum of Nodes Between 0s
}
System.out.println(head.data);
}
// Driver Code
public static void main(String[] args)
{
Node head = new Node(3);
head.next = new Node(2);
head.next.next = new Node(0);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
head.next.next.next.next.next = new Node(0);
head.next.next.next.next.next.next = new Node(6);
head.next.next.next.next.next.next.next = new Node(7);
inPlaceStore(head);
}
}
Output:
Source
https://www.geeksforgeeks.org/linked-list-sum-nodes-0s/
797
Chapter 130
Solution : One procedure X that follows uses the disjoint-set operations to compute the
connected components of a graph. Once X has pre-processed the graph, the procedure Y
answers queries about whether two vertices are in the same connected component. Below
figure shows the collection of disjoint sets after processing each edge.
798
Chapter 130. Linked List representation of Disjoint Set Data Structures
Figure (a) Linked-list representations of two sets. Set S1 contains members d, f, and g,
799
Chapter 130. Linked List representation of Disjoint Set Data Structures
Above three figures are taken from the Cormen book. Above Figure shows a simple
way to implement a disjoint-set data structure: each set is represented by its own linked
list. The object for each set has attributes head, pointing to the 1st object in the list, and
tail, pointing to the last object.
Each object in the list contains a set member, a pointer to the next object in the list, and
a pointer back to the set object. Within each linked list, the objects may appear in any
order. The representative is the set member in the 1st object in the list.
To carry out MAKE-SET (x), we create a new linked list whose only object is x. For
FIND-SET(x), we just follow the pointer from x back to its set object and then return
the member in the object that head points to. For example, in the Figure, the call
FIND-SET(g) would return f.
Algorithm:
Letting x denote an object, we wish to support the following operations:
MAKE-SET(x) creates a new set whose only member (and thus representative) is x. Since
the sets are disjoint, we require that x not already be in some other set.
UNION (x, y) unites the dynamic sets that contain x and y, say Sx and Sy , into a new
set that is the union of these two sets. We assume that the two sets are disjoint prior to the
operation. The representative of the resulting set is any member of Sx U Sy , although many
implementations of UNION specifically choose the representative of either Sx or Sy as the
new representative. Since we require the sets in the collection to be disjoint, conceptually
we destroy sets Sx and Sy , removing them from the collection S. In practice, we often absorb
the elements of one of the sets into the other set.
FIND-SET(x) returns a pointer to the representative of the (unique) set containing x.
Based on the above explanation, below are implementations:
800
Chapter 130. Linked List representation of Disjoint Set Data Structures
Node *next;
Item *itemPtr;
};
public:
void makeset(int a);
Item* find(int key);
void Union(Item *i1, Item *i2);
};
801
Chapter 130. Linked List representation of Disjoint Set Data Structures
delete set2;
}
// Driver code
int main()
{
ListSet a;
a.makeset(13); //a new set is made with one object only
a.makeset(25);
a.makeset(45);
a.makeset(65);
a.Union(a.find(65), a.find(45));
802
Chapter 130. Linked List representation of Disjoint Set Data Structures
Output:
find(13): 0x1aa3c20
find(25): 0x1aa3ca0
find(65): 0x1aa3d70
find(45): 0x1aa3c80
Union(find(65), find(45))
find(65]): 0x1aa3d70
find(45]): 0x1aa3d70
Note: The node address will change every time, we run the program.
Time complexities of MAKE-SET and FIND-SET are O(1). Time complexity fir UNION is
O(n).
Source
https://www.geeksforgeeks.org/linked-list-representation-disjoint-set-data-structures/
803
Chapter 131
804
Chapter 131. Linked List vs Array
Deletion is also expensive with arrays until unless some special techniques are used. For
example, to delete 1010 in id[], everything after 1010 has to be moved.
So Linked list provides following two advantages over arrays
1) Dynamic size
2) Ease of insertion/deletion
Linked lists have following drawbacks:
1) Random access is not allowed. We have to access elements sequentially starting from the
first node. So we cannot do binary search with linked lists.
2) Extra memory space for a pointer is required with each element of the list.
3) Arrays have better cache locality that can make a pretty big difference in performance.
References:
http://cslibrary.stanford.edu/103/LinkedListBasics.pdf
Source
https://www.geeksforgeeks.org/linked-list-vs-array/
805
Chapter 132
806
Chapter 132. Linked List | Set 1 (Introduction)
the first node. So we cannot do binary search with linked lists efficiently with its default
implementation. Read about it here.
2) Extra memory space for a pointer is required with each element of the list.
3) Not cache friendly. Since array elements are contiguous locations, there is locality of
reference which is not there in case of linked lists.
Representationv:
A linked list is represented by a pointer to the first node of the linked list. The first node
is called head. If the linked list is empty, then value of head is NULL.
Each node in a list consists of at least two parts:
1) data
2) Pointer (Or Reference) to the next node
In C, we can represent a node using structures. Below is an example of a linked list node
with an integer data.
In Java, LinkedList can be represented as a class and a Node as a separate class. The
LinkedList class contains a reference of Node class type.
Java
class LinkedList
{
Node head; // head of list
Python
807
Chapter 132. Linked List | Set 1 (Introduction)
# Node class
class Node:
First Simple Linked List in C Let us create a simple linked list with 3 nodes.
C
struct Node
{
int data;
struct Node *next;
};
808
Chapter 132. Linked List | Set 1 (Introduction)
809
Chapter 132. Linked List | Set 1 (Introduction)
head
|
|
+---+---+ +---+---+ +----+------+
| 1 | o----->| 2 | o-----> | 3 | NULL |
+---+---+ +---+---+ +----+------+
return 0;
}
Java
810
Chapter 132. Linked List | Set 1 (Introduction)
Python
# Node class
class Node:
811
Chapter 132. Linked List | Set 1 (Introduction)
llist.head = Node(1)
second = Node(2)
third = Node(3)
'''
Three nodes have been created.
We have references to these three blocks as first,
second and third
'''
Now next of first Node refers to second. So they
both are linked.
812
Chapter 132. Linked List | Set 1 (Introduction)
'''
Now next of second Node refers to third. So all three
nodes are linked.
struct Node
{
int data;
struct Node *next;
};
int main()
{
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
813
Chapter 132. Linked List | Set 1 (Introduction)
printList(head);
return 0;
}
Java
814
Chapter 132. Linked List | Set 1 (Introduction)
llist.printList();
}
}
Python
# Node class
class Node:
815
Chapter 132. Linked List | Set 1 (Introduction)
llist.head = Node(1)
second = Node(2)
third = Node(3)
llist.printList()
Output:
1 2 3
Important Links :
Source
https://www.geeksforgeeks.org/linked-list-set-1-introduction/
816
Chapter 133
Java
/* Node Class */
class Node
{
int data;
Node next;
817
Chapter 133. Linked List | Set 2 (Inserting a node)
Python
# Node class
class Node:
In this post, methods to insert a new node in linked list are discussed. A node can be added
in three ways
1) At the front of the linked list
2) After a given node.
3) At the end of the linked list.
Add a node at the front: (A 4 steps process)
The new node is always added before the head of the given Linked List. And newly
added node becomes the new head of the Linked List. For example if the given Linked
List is 10->15->20->25 and we add an item 5 at the front, then the Linked List becomes
5->10->15->20->25. Let us call the function that adds at the front of the list is push().
The push() must receive a pointer to the head pointer, because push must change the head
pointer to point to the new node (See this)
818
Chapter 133. Linked List | Set 2 (Inserting a node)
Java
819
Chapter 133. Linked List | Set 2 (Inserting a node)
Python
820
Chapter 133. Linked List | Set 2 (Inserting a node)
Java
821
Chapter 133. Linked List | Set 2 (Inserting a node)
Python
822
Chapter 133. Linked List | Set 2 (Inserting a node)
/* 4. If the Linked List is empty, then make the new node as head */
if (*head_ref == NULL)
{
*head_ref = new_node;
return;
}
Java
823
Chapter 133. Linked List | Set 2 (Inserting a node)
return;
}
Python
Time complexity of append is O(n) where n is the number of nodes in linked list. Since
there is a loop from head to end, the function does O(n) work.
This method can also be optimized to work in O(1) by keeping an extra pointer to tail of
linked list/
824
Chapter 133. Linked List | Set 2 (Inserting a node)
Following is a complete program that uses all of the above methods to create a
linked list.
C
825
Chapter 133. Linked List | Set 2 (Inserting a node)
new_node->data = new_data;
/* 4. If the Linked List is empty, then make the new node as head */
if (*head_ref == NULL)
{
*head_ref = new_node;
return;
}
826
Chapter 133. Linked List | Set 2 (Inserting a node)
}
}
return 0;
}
Java
827
Chapter 133. Linked List | Set 2 (Inserting a node)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
828
Chapter 133. Linked List | Set 2 (Inserting a node)
829
Chapter 133. Linked List | Set 2 (Inserting a node)
// 1->7->6->4->NUllist
llist.append(4);
Python
# Node class
class Node:
830
Chapter 133. Linked List | Set 2 (Inserting a node)
831
Chapter 133. Linked List | Set 2 (Inserting a node)
def printList(self):
temp = self.head
while (temp):
print temp.data,
temp = temp.next
# Insert 8, after 7. So linked list becomes 1 -> 7-> 8-> 6-> 4-> None
llist.insertAfter(llist.head.next, 8)
Output:
Source
https://www.geeksforgeeks.org/linked-list-set-2-inserting-a-node/
832
Chapter 134
Since every node of linked list is dynamically allocated using malloc() in C, we need to call
free() for freeing memory allocated for the node to be deleted.
833
Chapter 134. Linked List | Set 3 (Deleting a node)
C/C++
834
Chapter 134. Linked List | Set 3 (Deleting a node)
push(&head, 7);
push(&head, 1);
push(&head, 3);
push(&head, 2);
Java
835
Chapter 134. Linked List | Set 3 (Deleting a node)
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
836
Chapter 134. Linked List | Set 3 (Deleting a node)
llist.push(7);
llist.push(1);
llist.push(3);
llist.push(2);
Python
# Node class
class Node:
class LinkedList:
837
Chapter 134. Linked List | Set 3 (Deleting a node)
self.head = None
temp = None
838
Chapter 134. Linked List | Set 3 (Deleting a node)
# Driver program
llist = LinkedList()
llist.push(7)
llist.push(1)
llist.push(3)
llist.push(2)
Output:
Improved By : mlv
Source
https://www.geeksforgeeks.org/linked-list-set-3-deleting-node/
839
Chapter 135
LinkedList in Java
import java.util.*;
840
Chapter 135. LinkedList in Java
object.add("B");
object.addLast("C");
object.addFirst("D");
object.add(2, "E");
object.add("F");
object.add("G");
System.out.println("Linked list : " + object);
if(status)
System.out.println("List contains the element 'E' ");
else
System.out.println("List doesn't contain the element 'E'");
Output:
841
Chapter 135. LinkedList in Java
Please write comments if you find anything incorrect, or you want to share more information
about the topic discussed above
Improved By : Chinmoy Lenka
Source
https://www.geeksforgeeks.org/linked-list-in-java/
842
Chapter 136
• Create a linked list using the characters of the first string as the data in the linked
list.
• Then one by one using all the remaining strings, iterate over the linked list deleting all
the nodes after the point where the string gets exhausted or linked list gets exhausted
or the characters do not match.
• The remaining data in linked list is the required longest common prefix.
843
Chapter 136. Longest Common Prefix using Linked List
844
Chapter 136. Longest Common Prefix using Linked List
845
Chapter 136. Longest Common Prefix using Linked List
deleteNodes(temp);
}
break;
}
int main()
{
string arr[] = { "geeksforgeeks", "geeks", "geek", "geezer",
"geekathon" };
int n = sizeof(arr) / sizeof(arr[0]);
printLongestCommonPrefix(head);
}
Output:
Source
https://www.geeksforgeeks.org/longest-common-prefix-using-linked-list/
846
Chapter 137
A simple solution is to use auxiliary arrays to store linked lists. Then print longest commons
suffix of two arrays.
The above solution requires extra space. We can save space by first doing reverse of both
linked lists. After reversing, we can easily find length of longest common prefix. Reversing
again to get the original lists back.
One important point here is, order of elements. We need to print nodes from n-th to end.
We use the above found count and print nodes in required order using two pointer approach.
847
Chapter 137. Longest common suffix of two linked lists
848
Chapter 137. Longest common suffix of two linked lists
849
Chapter 137. Longest common suffix of two linked lists
printLastNNode(h1, count);
}
longestCommSuffix(h1, h2);
return 0;
}
Output:
gni
Source
https://www.geeksforgeeks.org/longest-common-suffix-two-linked-lists/
850
Chapter 138
Input : 8 -> 5 -> 7 -> 10 -> 9 -> 11 -> 12 -> 13 -> NULL
Output : Number of continuously increasing elements = 4
Increasing linked list : 9 11 12 13
The idea is to traverse singly linked list and compare curr->data with curr->next->data
where curr is current node being traversed. If curr->data is smaller then curr->next->data
then curr pointer point to curr->next and increment the length (continuous increasing
element) by one. If the condition is false then compare the length with max and if max is
less than len then assign the len value to max. Continue this process until head not equal
to NULL. Also find the starting index of continuous increasing element. Next traverse the
linked list and display the continuous increasing element in linked list.
851
Chapter 138. Longest increasing sublist in a linked list
struct Node {
int data;
struct Node* next;
};
curr_len = 1;
}
total_count++;
}
852
Chapter 138. Longest increasing sublist in a linked list
i++;
}
}
// Drier functions
int main()
{
// Create a node and initialize with NULL
struct Node* head = NULL;
853
Chapter 138. Longest increasing sublist in a linked list
Output:
Linked list:
15 18 5 8 11 12
Number of continuously increasing element in list :4
Increasing linked list
5 8 11 12
Source
https://www.geeksforgeeks.org/longest-increasing-sublist-linked-list/
854
Chapter 139
Input : 5
Output : 3
Explanation :
N=5
Soldier 1 2 3 4 5 (5 soldiers)
In first go 1 3 5 (remains) as 2 and 4 killed by 1 and 3.
In second go 3 as 5 killed 1 and 3rd kill 5 soldier 3 remains alive.
Input : 100
Output : 73
Explanation :
N = 10
Soldiers 1 2 3 4 5 6 7 8 9 10 (10 soldiers)
In first 1 3 5 7 9 as 2 4 6 8 10 were killed by 1 3 5 7 and 9.
In second 1 5 9 as 9 kill 1 and in turn 5 kill 9th soldier.
In third 5 5th soldiers remain alive
Approach : The idea is to use circular linked list. A circular linked list is made based
on number of soldier N. As rule state you have to kill your adjacent soldier and handover
855
Chapter 139. Lucky alive person in a circle | Code Solution to sword puzzle
the sword to the next soldier who in turn kill his adjacent soldier and handover sword to
the next soldier. So in circular linked list the adjacent soldier are killed and the remaining
soldier fights against each other in a circular way and a single soldier survive who is not
killed by anyone.
// Node structure
struct Node {
int data;
struct Node* next;
};
856
Chapter 139. Lucky alive person in a circle | Code Solution to sword puzzle
temp = curr;
curr = curr->next;
temp->next = curr->next;
return res;
}
// Driver code
int main()
{
int N = 100;
cout << alivesol(N) << endl;
return 0;
}
Output:
73
Source
https://www.geeksforgeeks.org/lucky-alive-person-circle/
857
Chapter 140
Input : 1->2->3->4->5->1->1->1->NULL
Output : 1
Explanation 1 occurs 4 times
Input :10->23->11->9->54->NULL
Output :NO majority element
Method 1(simple)
Run two loops starting from head and count frequency of each element iteratively. Print the
element whose frequency is greater than or equal to n/2. In this approach time complexity
will be O(n*n) where n is the number of nodes in the linked list.
C++
858
Chapter 140. Majority element in a linked list
p = p->next;
total_count++;
}
859
Chapter 140. Majority element in a linked list
// create linked
push(&head, 1);
push(&head, 1);
push(&head, 1);
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
if (res != (-1))
cout << "Majority element is " << res;
else
cout << "No majority element";
return 0;
}
C++
860
Chapter 140. Majority element in a linked list
int total_count = 0;
while (p != NULL) {
p = p->next;
total_count++;
}
861
Chapter 140. Majority element in a linked list
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
if (res != (-1))
cout << "majority element is " << res;
else
cout << "NO majority elemenet";
return 0;
}
majority element is 1
Source
https://www.geeksforgeeks.org/majority-element-in-a-linked-list/
862
Chapter 141
Algorithm
1) Traverse the first linked list till k-th point
2) Make backup of the k-th node
3) Traverse the linked linked list till end
4) Attach the last node with k-th node
863
Chapter 141. Make a loop at k-th position in a linked list
864
Chapter 141. Make a loop at k-th position in a linked list
int count = 0;
while (ptr != NULL)
{
ptr = ptr->next;
count++;
}
return count;
}
makeloop(&head, k);
Output:
Given list
1 2 3 4 5 6 7
Modified list
1 2 3 4 5 6 7
Source
https://www.geeksforgeeks.org/make-loop-k-th-position-linked-list/
865
Chapter 142
Input : 1 2 3 4 5
Output : 3 1 2 4 5
Input : 1 2 3 4 5 6
Output : 4 1 2 3 5 6
The idea is to first find middle of a linked list using two pointers, first one moves one at a
time and second one moves two at a time. When second pointer reaches end, first reaches
866
Chapter 142. Make middle node head in a linked list
middle. We also keep track of previous of first pointer so that we can remove middle node
from its current position and can make it head.
867
Chapter 142. Make middle node head in a linked list
new_node->data = new_data;
/* Driver function*/
int main()
{
// Create a list of 5 nodes
struct Node* head = NULL;
int i;
for (i = 5; i > 0; i--)
push(&head, i);
setMiddleHead(&head);
return 0;
}
868
Chapter 142. Make middle node head in a linked list
Java
869
Chapter 142. Make middle node head in a linked list
/* Driver function*/
public static void main(String args[])
{
// Create a list of 5 nodes
head = null;
int i;
for (i = 5; i > 0; i--)
push(i);
setMiddleHead();
870
Chapter 142. Make middle node head in a linked list
}
// This code is contributed by Sumit Ghosh
Output:
list before: 1 2 3 4 5
list After : 3 1 2 4 5
Source
https://www.geeksforgeeks.org/make-middle-node-head-linked-list/
871
Chapter 143
Method 1:
Iteratively count the frequency of each character in a string and return the one which has
maximum occurrence.
872
Chapter 143. Maximum occurring character in a linked list
while (p != NULL) {
q = q->next;
}
p = p->next;
}
return res;
}
873
Chapter 143. Maximum occurring character in a linked list
return 0;
}
Output:
Time complexityO(N*N)
Method 2: (use count array)
Create a count array and count each character frequency return the maximum occurring
character.
p = head;
874
Chapter 143. Maximum occurring character in a linked list
Output:
Time complexityO(N)
Source
https://www.geeksforgeeks.org/maximum-occurring-character-linked-list/
875
Chapter 144
Solution:
This question is solved and very well explained at http://www.linuxjournal.com/article/
6828.
We also recommend to read http://en.wikipedia.org/wiki/XOR_linked_list
Source
https://www.geeksforgeeks.org/memory-efficient-doubly-linked-list/
876
Chapter 145
Input: k = 3, n = 4
list1 = 1->3->5->7->NULL
list2 = 2->4->6->8->NULL
list3 = 0->9->10->11
Output:
0->1->2->3->4->5->6->7->8->9->10->11
Method 1 (Simple)
A Simple Solution is to initialize result as first list. Now traverse all lists starting from
second list. Insert every node of currently traversed list into result in a sorted way. Time
complexity of this solution is O(N2 ) where N is total number of nodes, i.e., N = kn.
877
Chapter 145. Merge K sorted linked lists | Set 1
/* Base cases */
if (a == NULL)
return (b);
else if(b == NULL)
return (a);
878
Chapter 145. Merge K sorted linked lists | Set 1
return result;
}
return arr[0];
}
879
Chapter 145. Merge K sorted linked lists | Set 1
temp->next = NULL;
return temp;
}
arr[0] = newNode(1);
arr[0]->next = newNode(3);
arr[0]->next->next = newNode(5);
arr[0]->next->next->next = newNode(7);
arr[1] = newNode(2);
arr[1]->next = newNode(4);
arr[1]->next->next = newNode(6);
arr[1]->next->next->next = newNode(8);
arr[2] = newNode(0);
arr[2]->next = newNode(9);
arr[2]->next->next = newNode(10);
arr[2]->next->next->next = newNode(11);
printList(head);
return 0;
}
Output :
0 1 2 3 4 5 6 7 8 9 10 11
Time Complexity of above algorithm is O(nk logk) as outer while loop in function mergeK-
Lists() runs log k times and every time we are processing nk elements.
Merge k sorted linked lists | Set 2 (Using Min Heap)
880
Chapter 145. Merge K sorted linked lists | Set 1
Source
https://www.geeksforgeeks.org/merge-k-sorted-linked-lists/
881
Chapter 146
Merge sort for singly linked list is already discussed. The important change here is to modify
the previous pointers also when merging two lists.
Below is the implementation of merge sort for doubly linked list.
C
882
Chapter 146. Merge Sort for Doubly Linked List
{
// If first linked list is empty
if (!first)
return second;
883
Chapter 146. Merge Sort for Doubly Linked List
884
Chapter 146. Merge Sort for Doubly Linked List
}
struct Node *temp = slow->next;
slow->next = NULL;
return temp;
}
// Driver program
int main(void)
{
struct Node *head = NULL;
insert(&head,5);
insert(&head,20);
insert(&head,4);
insert(&head,3);
insert(&head,30);
insert(&head,10);
head = mergeSort(head);
printf("\n\nLinked List after sorting\n");
print(head);
return 0;
}
Java
/* Node Class */
static class Node {
int data;
Node next, prev;
885
Chapter 146. Merge Sort for Doubly Linked List
886
Chapter 146. Merge Sort for Doubly Linked List
}
}
Python
887
Chapter 146. Merge Sort for Doubly Linked List
self.next = None
self.prev = None
class DoublyLinkedList:
second = self.split(tempHead)
888
Chapter 146. Merge Sort for Doubly Linked List
temp = slow.next
slow.next = None
return temp
# 1. Allocates node
# 2. Put the data in it
new_node = Node(new_data)
889
Chapter 146. Merge Sort for Doubly Linked List
Output:
Source
https://www.geeksforgeeks.org/merge-sort-for-doubly-linked-list/
890
Chapter 147
MergeSort(headRef)
1) If head is NULL or there is only one element in the Linked List
then return.
2) Else divide the linked list into two halves.
FrontBackSplit(head, &a, &b); /* a and b are two halves */
3) Sort the two halves a and b.
MergeSort(a);
MergeSort(b);
4) Merge the sorted a and b (using SortedMerge() discussed here)
and update the head pointer using headRef.
*headRef = SortedMerge(a, b);
891
Chapter 147. Merge Sort for Linked Lists
{
int data;
struct Node* next;
};
/* function prototypes */
struct Node* SortedMerge(struct Node* a, struct Node* b);
void FrontBackSplit(struct Node* source,
struct Node** frontRef, struct Node** backRef);
/* Base cases */
if (a == NULL)
return(b);
else if (b==NULL)
return(a);
892
Chapter 147. Merge Sort for Linked Lists
{
result = a;
result->next = SortedMerge(a->next, b);
}
else
{
result = b;
result->next = SortedMerge(a, b->next);
}
return(result);
}
/* UTILITY FUNCTIONS */
/* Split the nodes of the given list into front and back halves,
and return the two lists using the reference parameters.
If the length is odd, the extra node should go in the front list.
Uses the fast/slow pointer strategy. */
void FrontBackSplit(struct Node* source,
struct Node** frontRef, struct Node** backRef)
{
struct Node* fast;
struct Node* slow;
slow = source;
fast = source->next;
893
Chapter 147. Merge Sort for Linked Lists
getchar();
return 0;
}
894
Chapter 147. Merge Sort for Linked Lists
Java
node mergeSort(node h)
{
// Base case : if head is null
if (h == null || h.next == null)
895
Chapter 147. Merge Sort for Linked Lists
{
return h;
}
896
Chapter 147. Merge Sort for Linked Lists
897
Chapter 147. Merge Sort for Linked Lists
http://cslibrary.stanford.edu/105/LinkedListProblems.pdf
Source
https://www.geeksforgeeks.org/merge-sort-for-linked-list/
898
Chapter 148
<script>
// To initialize a linkedlist
function LinkedList(list) {
this.head = list || null
}
899
Chapter 148. Merge Sort for Linked Lists in JavaScript
LinkedList.prototype.insert = function(data) {
else {
900
Chapter 148. Merge Sort for Linked Lists in JavaScript
let count = 0;
let countList = list
let leftPart = list;
let leftPointer = list;
let rightPart = null;
let rightPointer = null;
901
Chapter 148. Merge Sort for Linked Lists in JavaScript
if (result.head == null) {
result.head = new Node(tempNode)
resultPointer = result.head
}
else {
resultPointer.next = new Node(tempNode)
resultPointer = resultPointer.next
}
}
resultPointer.next = pointerRight
902
Chapter 148. Merge Sort for Linked Lists in JavaScript
l.insert(3)
l.insert(2)
l.insert(1)
// Print the linked list
l.iterate()
Output
Source
https://www.geeksforgeeks.org/merge-sort-linked-lists-javascript/
903
Chapter 149
Merge a linked list into another linked list at alternate positions - GeeksforGeeks
Given two linked lists, insert nodes of second list into first list at alternate positions of first
list.
For example, if first list is 5->7->17->13->11 and second is 12->10->2->4->6, the first
list should become 5->12->7->10->17->2->13->4->11->6 and second list should become
empty. The nodes of second list should only be inserted when there are positions available.
For example, if the first list is 1->2->3 and second list is 4->5->6->7->8, then first list
should become 1->4->2->5->3->6 and second list to 7->8.
Use of extra space is not allowed (Not allowed to create additional nodes), i.e., insertion
must be done in-place. Expected time complexity is O(n) where n is number of nodes in
first list.
The idea is to run a loop while there are available positions in first loop and insert nodes
of second list by changing pointers. Following are C and Java implementations of this
approach.
C/C++
904
Chapter 149. Merge a linked list into another linked list at alternate positions
905
Chapter 149. Merge a linked list into another linked list at alternate positions
push(&q, 8);
push(&q, 7);
push(&q, 6);
push(&q, 5);
push(&q, 4);
printf("Second Linked List:\n");
printList(q);
merge(p, &q);
getchar();
return 0;
}
Java
906
Chapter 149. Merge a linked list into another linked list at alternate positions
907
Chapter 149. Merge a linked list into another linked list at alternate positions
System.out.print(temp.data+" ");
temp = temp.next;
}
System.out.println();
}
llist2.push(8);
llist2.push(7);
llist2.push(6);
llist2.push(5);
llist2.push(4);
llist1.merge(llist2);
Python
908
Chapter 149. Merge a linked list into another linked list at alternate positions
self.data = d
self.next = None
909
Chapter 149. Merge a linked list into another linked list at alternate positions
llist2.push(8)
llist2.push(7)
llist2.push(6)
llist2.push(5)
llist2.push(4)
llist2.printList()
llist1.merge(llist2)
Output:
This article is contributed by Chandra Prakash. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/merge-a-linked-list-into-another-linked-list-at-alternate-positions/
910
Chapter 150
Merge first half and reversed second half of the linked list alternatively - GeeksforGeeks
Given a linked list, the task is to rearrange the linked list in the following manner:
Examples:
Input: 1->2->3->4->5
Output: 1->5->2->4->3
Input: 1->2->3->4->5->6
Output: 1->6->2->5->3->4
Approach: Initially find the mid node of the linked list. The approach has been discussed
here. Reverse the linked list from mid to end. Once the linked list is reversed, traverse from
the start and insert a node from the first half of the list and another node from the back
half of the linked list simultaneously. Continue this process until the middle node is reached.
Once the middle node is reached, point the node just before the middle node to NULL.
Below is the implementation of the above approach:
C++
911
Chapter 150. Merge first half and reversed second half of the linked list alternatively
struct node {
int data;
struct node* next;
};
912
Chapter 150. Merge first half and reversed second half of the linked list alternatively
// allocate memory
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->data = val;
// if first node
if (*start == NULL)
*start = temp;
else {
913
Chapter 150. Merge first half and reversed second half of the linked list alternatively
// Driver Code
int main()
{
// Odd Length Linked List
struct node* start = NULL;
insertNode(&start, 1);
insertNode(&start, 2);
insertNode(&start, 3);
insertNode(&start, 4);
insertNode(&start, 5);
return 0;
}
Java
class node
{
int data;
node next;
node(int key)
914
Chapter 150. Merge first half and reversed second half of the linked list alternatively
{
data = key;
next = null;
}
}
class GFG
{
// Function to reverse
// Linked List
public static node reverseLL(node root)
{
// root needs to be
// upated after reversing
root = prev;
return root;
}
// Function to modify
// Linked List
public static void modifyLL( node root)
{
// Find the mid node
node slow_ptr = root, fast_ptr = root;
while (fast_ptr != null &&
fast_ptr.next != null)
{
fast_ptr = fast_ptr.next.next;
slow_ptr = slow_ptr.next;
}
915
Chapter 150. Merge first half and reversed second half of the linked list alternatively
slow_ptr.next = null;
// Function to insert
// node after the end
public static node insertNode(node start,
int val)
{
// allocate memory
node temp = new node(val);
// if first node
if (start == null)
start = temp;
else
{
return start;
916
Chapter 150. Merge first half and reversed second half of the linked list alternatively
// function to print
// the linked list
public static void display(node start)
{
node temp = start;
// Driver Code
public static void main(String args[])
{
// Odd Length Linked List
node start = null;
start = insertNode(start, 1);
start = insertNode(start, 2);
start = insertNode(start, 3);
start = insertNode(start, 4);
start = insertNode(start, 5);
917
Chapter 150. Merge first half and reversed second half of the linked list alternatively
Output:
Source
https://www.geeksforgeeks.org/merge-first-half-and-reversed-second-half-of-the-linked-list-alternatively/
918
Chapter 151
Input: k = 3, n = 4
list1 = 1->3->5->7->NULL
list2 = 2->4->6->8->NULL
list3 = 0->9->10->11
Output:
0->1->2->3->4->5->6->7->8->9->10->11
struct Node {
int data;
struct Node* next;
919
Chapter 151. Merge k sorted linked lists | Set 2 (Using Min Heap)
};
else {
// insert 'top' at the end of the merged list so far
920
Chapter 151. Merge k sorted linked lists | Set 2 (Using Min Heap)
last->next = top;
return new_node;
}
921
Chapter 151. Merge k sorted linked lists | Set 2 (Using Min Heap)
arr[1] = newNode(2);
arr[1]->next = newNode(4);
arr[1]->next->next = newNode(6);
arr[1]->next->next->next = newNode(8);
arr[2] = newNode(0);
arr[2]->next = newNode(9);
arr[2]->next->next = newNode(10);
arr[2]->next->next->next = newNode(11);
return 0;
}
Output:
0 1 2 3 4 5 6 7 8 9 10 11
Source
https://www.geeksforgeeks.org/merge-k-sorted-linked-lists-set-2-using-min-heap/
922
Chapter 152
1. Merge the two sorted linked list in sorted manner. Refer recursive approach of this
post. Let the final obtained list be head.
2. Remove duplicates from sorted linked list head.
// structure of a node
struct Node {
int data;
Node* next;
923
Chapter 152. Merge two sorted linked list without duplicates
};
// put in data
temp->data = data;
temp->next = NULL;
return temp;
}
/* Base cases */
if (a == NULL)
return (b);
else if (b == NULL)
return (a);
924
Chapter 152. Merge two sorted linked list without duplicates
if (current == NULL)
return;
return head;
}
925
Chapter 152. Merge two sorted linked list without duplicates
head1->next = getNode(1);
head1->next->next = getNode(4);
head1->next->next->next = getNode(5);
head1->next->next->next->next = getNode(7);
// head2: 2->4->7->9
Node* head2 = getNode(2);
head2->next = getNode(4);
head2->next->next = getNode(7);
head2->next->next->next = getNode(9);
Node* head3;
printList(head3);
return 0;
}
Output:
1 2 4 5 7 9
Source
https://www.geeksforgeeks.org/merge-two-sorted-linked-list-without-duplicates/
926
Chapter 153
927
Chapter 153. Merge two sorted linked lists
/* pull off the front node of the source and put it in dest */
void MoveNode(struct Node** destRef, struct Node** sourceRef);
tail = tail->next;
}
return(dummy.next);
}
/* UTILITY FUNCTIONS */
/* MoveNode() function takes the node from the front of the
source, and move it to the front of the dest.
It is an error to call this with the source list empty.
928
Chapter 153. Merge two sorted linked lists
source == {1, 2, 3}
dest == {1, 2, 3}
929
Chapter 153. Merge two sorted linked lists
}
}
push(&b, 20);
push(&b, 3);
push(&b, 2);
return 0;
}
Output :
930
Chapter 153. Merge two sorted linked lists
while(1)
{
if (a == NULL)
{
*lastPtrRef = b;
break;
}
else if (b==NULL)
{
*lastPtrRef = a;
break;
}
if(a->data <= b->data)
{
MoveNode(lastPtrRef, &a);
}
else
{
MoveNode(lastPtrRef, &b);
}
C/C++
/* Base cases */
if (a == NULL)
return(b);
931
Chapter 153. Merge two sorted linked lists
else if (b==NULL)
return(a);
Python3
# Node class
class Node:
def __init__(self, data):
self.data = data
self.next = None
while temp :
print(temp.data, end="->")
temp = temp.next
932
Chapter 153. Merge two sorted linked lists
if self.head is None:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
else:
# If List2's data is greater than or equal List1's
# data assign temp to head2
temp = head2
933
Chapter 153. Merge two sorted linked lists
# Driver Function
if __name__ == '__main__':
Source
https://www.geeksforgeeks.org/merge-two-sorted-linked-lists/
934
Chapter 154
Merge two sorted linked lists such that merged list is in reverse order - GeeksforGeeks
Given two linked lists sorted in increasing order. Merge them such a way that the result list
is in decreasing order (reverse order).
Examples:
Input: a: 5->10->15->40
b: 2->3->20
Output: res: 40->20->15->10->5->3->2
Input: a: NULL
b: 2->3->20
Output: res: 20->3->2
935
Chapter 154. Merge two sorted linked lists such that merged list is in reverse order
936
Chapter 154. Merge two sorted linked lists such that merged list is in reverse order
return res;
}
937
Chapter 154. Merge two sorted linked lists such that merged list is in reverse order
{
while (Node!=NULL)
{
cout << Node->key << " ";
Node = Node->next;
}
}
Node *b = newNode(2);
b->next = newNode(3);
b->next->next = newNode(20);
938
Chapter 154. Merge two sorted linked lists such that merged list is in reverse order
return 0;
}
Java
// Java program to merge two sorted linked list such that merged
// list is in reverse order
/* Node Class */
static class Node {
int data;
Node next;
// resultant node
Node res = null;
939
Chapter 154. Merge two sorted linked lists such that merged list is in reverse order
return res;
940
Chapter 154. Merge two sorted linked lists such that merged list is in reverse order
}
}
Output:
This solution traverses both lists only once, doesn’t require reverse and works in-place.
This article is contributed by Mohammed Raqeeb. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/merge-two-sorted-linked-lists-such-that-merged-list-is-in-reverse-order/
941
Chapter 155
Method 1 (Recursive)
struct Node
{
942
Chapter 155. Merge two sorted lists (in-place)
int data;
struct Node *next;
};
// Driver program
int main()
943
Chapter 155. Merge two sorted lists (in-place)
{
Node *head1 = newNode(1);
head1->next = newNode(3);
head1->next->next = newNode(5);
printList(mergedhead);
return 0;
}
Output:
0 1 2 3 4 5
Method 2 (Iterative)
struct Node
{
int data;
struct Node *next;
};
944
Chapter 155. Merge two sorted lists (in-place)
945
Chapter 155. Merge two sorted lists (in-place)
{
// if more nodes in first list
if (next1->next)
{
next1 = next1->next;
curr1 = curr1->next;
}
// Driver program
int main()
{
struct Node *head1 = newNode(1);
head1->next = newNode(3);
head1->next->next = newNode(5);
946
Chapter 155. Merge two sorted lists (in-place)
head2->next = newNode(2);
head2->next->next = newNode(4);
printList(mergedhead);
return 0;
}
Output:
0 1 2 3 4 5
Source
https://www.geeksforgeeks.org/merge-two-sorted-lists-place/
947
Chapter 156
Input : 2->2->0->4->0->8
Output : 4->4->8->0->0->0
Input : 0->2->2->2->0->6->6->0->0->8
Output : 4->2->12->8->0->0->0->0->0->0
1. ptr = head
2. while (ptr && ptr->next)
3. if (ptr->data == 0) || (ptr->data != ptr->next->data)
4. ptr = ptr->next
5. else
6. ptr->data = 2 * ptr->data
7. ptr->next->data = 0
8. ptr = ptr->next->next
948
Chapter 156. Modify and Rearrange List
After modifying the list segregate the valid (non-zero) and invalid (zero) elements. It is
same as Segregating Even and Odd nodes in a Linked list.
// structure of a node
struct Node {
int data;
Node* next;
};
949
Chapter 156. Modify and Rearrange List
if (validStart == NULL) {
validStart = currentNode;
validEnd = validStart;
}
else {
validEnd->next = currentNode;
validEnd = validEnd->next;
}
}
950
Chapter 156. Modify and Rearrange List
else {
951
Chapter 156. Modify and Rearrange List
printList(head);
head = modifyAndRearrangeList(head);
return 0;
}
Output:
Original List: 2 2 0 4 0 8
Modified List: 4 4 8 0 0 0
Source
https://www.geeksforgeeks.org/modify-rearrange-list/
952
Chapter 157
1. Split the list from the middle. Perform front and back split. If the number of
elements is odd, the extra element should go in the 1st(front) list.
2. Reverse the 2nd(back) list.
3. Perfrom the required subtraction while traversing both list simultaneously.
4. Again reverse the 2nd list.
5. Concatenate the 2nd list back to the end of the 1st list.
953
Chapter 157. Modify contents of Linked List
slow = head;
fast = head->next;
954
Chapter 157. Modify contents of Linked List
if (fast != NULL)
{
slow = slow->next;
fast = fast->next;
}
}
front = front->next;
back = back->next;
}
}
955
Chapter 157. Modify contents of Linked List
// the 1st(front) list and returns the head of the new list
struct Node* concatFrontAndBackList(struct Node *front,
struct Node *back)
{
struct Node *head = front;
front->next = back;
return head;
}
956
Chapter 157. Modify contents of Linked List
return;
Output:
Modified List:
-8 -> 2 -> -4 -> 12 -> 7 -> 10
C++
957
Chapter 157. Modify contents of Linked List
// allocate node
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
958
Chapter 157. Modify contents of Linked List
return slow ;
}
while(slow)
{
s.push( slow->data ) ;
slow = slow->next ;
}
959
Chapter 157. Modify contents of Linked List
Output:
Modified List:
-8 -> 2 -> -4 -> 12 -> 7 -> 10
Source
https://www.geeksforgeeks.org/modify-contents-linked-list/
960
Chapter 158
A simple solution is to one by one find all occurrences of given key in linked list. For
every found occurrence, insert it at the end. We do it till all occurrences of given key are
moved to end.
Time Complexity : O(n2 )
Efficient Solution 1 : is to keep two pointers:
pCrawl => Pointer to traverse the whole list one by one.
pKey => Pointer to an occurrence of key if a key is found. Else same as pCrawl.
We start both of the above pointers from head of linked list. We move pKey only when
pKey is not pointing to a key. We always move pCrawl. So when pCrawl and pKey are
not same, we must have found a key which lies before pCrawl, so we swap data of pCrawl
and pKey, and move pKey to next location. The loop invariant is, after swapping of data,
all elements from pKey to pCrawl are keys.
Below is the C++ implementation of this approach.
961
Chapter 158. Move all occurrences of an element to end in a linked list
// Traverse list
struct Node *pCrawl = head;
while (pCrawl != NULL)
{
// If current pointer is not same as pointer
// to a key location, then we must have found
// a key in linked list. We swap data of pCrawl
// and pKey and move pKey to next position.
962
Chapter 158. Move all occurrences of an element to end in a linked list
// Driver code
int main()
{
Node *head = newNode(10);
head->next = newNode(20);
head->next->next = newNode(10);
head->next->next->next = newNode(30);
head->next->next->next->next = newNode(40);
head->next->next->next->next->next = newNode(10);
head->next->next->next->next->next->next = newNode(60);
return 0;
}
Output:
963
Chapter 158. Move all occurrences of an element to end in a linked list
Efficient Solution 2 :
1. Traverse the linked list and take a pointer at tail.
2. Now, check for the key and node->data, if they are equal, move the node to last-next,
else move
ahead.
Java
// Node class
class Node{
int data;
Node next;
class gfg{
if(head==null){
return null;
}
while(tail.next !=null){
tail=tail.next;
}
964
Chapter 158. Move all occurrences of an element to end in a linked list
// Driver Code
public static void main(String args[]){
root = new Node(5);
root.next = new Node(2);
root.next.next = new Node(2);
root.next.next.next = new Node(7);
root.next.next.next.next = new Node(2);
root.next.next.next.next.next = new Node(2);
root.next.next.next.next.next.next = new Node(2);
965
Chapter 158. Move all occurrences of an element to end in a linked list
int key = 2;
System.out.println("Linked List before operations :");
display(root);
System.out.println("\nLinked List after operations :");
root = keyToEnd(root, key);
display(root);
}
}
Source
https://www.geeksforgeeks.org/move-occurrences-element-end-linked-list/
966
Chapter 159
Input : 0 1 0 1 2 0 5 0 4 0
Output :0 0 0 0 0 1 1 2 5 4
Input :1 1 2 3 0 0 0
Output :0 0 0 1 1 2 3
A simple solution is to store all linked list element in an array. Then move all elements
of array to beginning. Finally copy array elements back to linked list.
An efficient solution is to traverse the linked list from second node. For every node with
0 value, we disconnect it from its current position and move the node to front.
967
Chapter 159. Move all zeros to the front of the linked list
// Move to beginning
curr->next = (*head);
*head = curr;
}
968
Chapter 159. Move all zeros to the front of the linked list
}
cout << "NULL";
}
return 0;
}
Output:
969
Chapter 159. Move all zeros to the front of the linked list
Source
https://www.geeksforgeeks.org/move-zeroes-front-linked-list/
970
Chapter 160
971
Chapter 160. Move first element to end of a given Linked List
/* UTILITY FUNCTIONS */
/* Function to add a node at the beginning
of Linked List */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node = new Node;
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
972
Chapter 160. Move first element to end of a given Linked List
{
struct Node* start = NULL;
moveToEnd(&start);
return 0;
}
Output:
Time Complexity: O(n) where n is the number of nodes in the given Linked List.
Source
https://www.geeksforgeeks.org/move-first-element-to-end-of-a-given-linked-list/
973
Chapter 161
974
Chapter 161. Move last element to front of a given Linked List
/* UTILITY FUNCTIONS */
/* Function to add a node at the begining of Linked List */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
975
Chapter 161. Move last element to front of a given Linked List
while(node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
}
moveToFront(&start);
return 0;
}
Java
void moveToFront()
{
976
Chapter 161. Move last element to front of a given Linked List
/* Utility functions */
977
Chapter 161. Move last element to front of a given Linked List
llist.moveToFront();
Output:
Time Complexity: O(n) where n is the number of nodes in the given Linked List.
Improved By : Soumith Bsv
Source
https://www.geeksforgeeks.org/move-last-element-to-front-of-a-given-linked-list/
978
Chapter 162
Multiply two numbers represented as linked lists into a third list - GeeksforGeeks
Given two numbers represented by linked lists, write a function that returns the head of the
new linked list that represents the number that is the product of those numbers.
Examples:
Input : 9->4->6
8->4
Output : 7->9->4->6->4
Input : 9->9->9->4->6->9
9->9->8->4->9
Output : 9->9->7->9->5->9->8->0->1->8->1
979
Chapter 162. Multiply two numbers represented as linked lists into a third list
980
Chapter 162. Multiply two numbers represented as linked lists into a third list
(*head_ref) = new_node;
}
981
Chapter 162. Multiply two numbers represented as linked lists into a third list
int carry = 0;
first_ptr = first;
while (first_ptr) {
first_ptr = first_ptr->next;
result_ptr2 = result_ptr2->next;
}
result_ptr1 = result_ptr1->next;
second_ptr = second_ptr->next;
}
982
Chapter 162. Multiply two numbers represented as linked lists into a third list
reverse(&second);
983
Chapter 162. Multiply two numbers represented as linked lists into a third list
printList(second);
return 0;
}
Output:
Note: we can take care of resultant node that can have more than 1 digit outside the loop
just traverse the result list and add carry to next digit before reversing.
Source
https://www.geeksforgeeks.org/multiply-two-numbers-represented-linked-lists-third-list/
984
Chapter 163
Input : 9->4->6
8->4
Output : 79464
Input : 3->2->1
1->2
Output : 3852
Solution:
Traverse both lists and generate the required numbers to be multiplied and then return the
multiplied values of the two numbers.
Algorithm to generate the number from linked list representation:
985
Chapter 163. Multiply two numbers represented by Linked Lists
Use the above algorithm with both of linked lists to generate the numbers.
Below is the program for multiplying two numbers represented as linked lists:
C++
986
Chapter 163. Multiply two numbers represented by Linked Lists
{
if (first)
{
num1 = num1*10 + first->data;
first = first->next;
}
if (second)
{
num2 = num2*10 + second->data;
second = second->next;
}
}
// Return multiplication of
// two numbers
return num1*num2;
}
987
Chapter 163. Multiply two numbers represented by Linked Lists
printList(second);
return 0;
}
Python3
def __repr__(self):
988
Chapter 163. Multiply two numbers represented by Linked Lists
str_repr = ""
while(next):
str_repr += str(next.data)
if next.next: str_repr += "->"
next = next.next
return str_repr
# Driver Code
989
Chapter 163. Multiply two numbers represented by Linked Lists
Output:
Improved By : harishkumar88
Source
https://www.geeksforgeeks.org/multiply-two-numbers-represented-linked-lists/
990
Chapter 164
A simple solution is to one by one consider every term of first polynomial and multiply it
with every term of second polynomial. Following is algorithm of this simple method.
multiply(A[0..m-1], B[0..n01])
1) Create a product array prod[] of size m+n-1.
2) Initialize all entries in prod[] as 0.
3) Travers array A[] and do following for every element A[i]
...(3.a) Traverse array B[] and do following for every element B[j]
prod[i+j] = prod[i+j] + A[i] * B[j]
4) Return prod[].
991
Chapter 164. Multiply two polynomials
#include <iostream>
using namespace std;
return prod;
}
992
Chapter 164. Multiply two polynomials
return 0;
}
Output
First polynomial is
5 + 0x^1 + 10x^2 + 6x^3
Second polynomial is
1 + 2x^1 + 4x^2
Product polynomial is
5 + 10x^1 + 30x^2 + 26x^3 + 52x^4 + 24x^5
Time complexity of the above solution is O(mn). If size of two polynomials same, then time
complexity is O(n2 ).
Can we do better?
There are methods to do multiplication faster than O(n2 ) time. These methods are mainly
based on divide and conquer. Following is one simple method that divides the given polyno-
mial (of degree n) into two polynomials one containing lower degree terms(lower than n/2)
and other containing higher degree terns (higher than or equal to n/2)
993
Chapter 164. Multiply two polynomials
So the above divide and conquer approach requires 4 multiplications and O(n) time to add
all 4 results. Therefore the time complexity is T(n) = 4T(n/2) + O(n). The solution of the
recurrence is O(n2 ) which is same as the above simple solution.
The idea is to reduce number of multiplications to 3 and make the recurrence as T(n) =
3T(n/2) + O(n)
How to reduce number of multiplications?
This requires a little trick similar toStrassen’s Matrix Multiplication. We do following 3
multiplications.
In Depth Explanation
Conventional polynomial multiplication uses 4 coefficient multiplications:
(a + b)(c + d) = ad + bc + ac + bd
The rest of the two components are exactly the middle coefficient for product of two poly-
nomials. Therefore, the product can be computed as:
994
Chapter 164. Multiply two polynomials
Sources:
http://www.cse.ust.hk/~dekai/271/notes/L03/L03.pdf
This article is contributed by Harsh. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above.
Improved By : Mr.L
Source
https://www.geeksforgeeks.org/multiply-two-polynomials-2/
995
Chapter 165
996
Chapter 165. Pairwise swap elements of a given linked list
/* UTILITY FUNCTIONS */
/* Function to swap two integers */
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
997
Chapter 165. Pairwise swap elements of a given linked list
pairWiseSwap(start);
return 0;
}
Java
void pairWiseSwap()
{
Node temp = head;
998
Chapter 165. Pairwise swap elements of a given linked list
int k = temp.data;
temp.data = temp.next.data;
temp.next.data = k;
temp = temp.next.next;
}
}
/* Utility functions */
999
Chapter 165. Pairwise swap elements of a given linked list
llist.pairWiseSwap();
Python
# Node class
class Node:
class LinkedList:
1000
Chapter 165. Pairwise swap elements of a given linked list
# Driver program
llist = LinkedList()
llist.push(5)
llist.push(4)
llist.push(3)
llist.push(2)
llist.push(1)
llist.pairwiseSwap()
Output:
1001
Chapter 165. Pairwise swap elements of a given linked list
Source
https://www.geeksforgeeks.org/pairwise-swap-elements-of-a-given-linked-list/
1002
Chapter 166
/* This program swaps the nodes of linked list rather than swapping the
field from the nodes.
Imagine a case where a node contains many fields, there will be plenty
of unnecessary swap calls. */
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
1003
Chapter 166. Pairwise swap elements of a given linked list by changing links
};
1004
Chapter 166. Pairwise swap elements of a given linked list by changing links
new_node->next = (*head_ref);
pairWiseSwap(&start);
getchar();
return 0;
}
Java
class LinkedList {
1005
Chapter 166. Pairwise swap elements of a given linked list by changing links
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
1006
Chapter 166. Pairwise swap elements of a given linked list by changing links
}
}
Output:
Time Complexity: Time complexity of the above program is O(n) where n is the number of
nodes in a given linked list. The while loop does a traversal of the given linked list.
Following is recursive implementation of the same approach. We change first two nodes
and recur for the remaining list. Thanks to geek and omer salem for suggesting this method.
C
1007
Chapter 166. Pairwise swap elements of a given linked list by changing links
/* This program swaps the nodes of linked list rather than swapping the
field from the nodes.
Imagine a case where a node contains many fields, there will be plenty
of unnecessary swap calls. */
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
// Change head
struct node* newhead = head->next;
1008
Chapter 166. Pairwise swap elements of a given linked list by changing links
return 0;
}
Java
1009
Chapter 166. Pairwise swap elements of a given linked list by changing links
class LinkedList {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
// Change head
Node newhead = node.next;
1010
Chapter 166. Pairwise swap elements of a given linked list by changing links
}
}
}
}
This article is contributed by Gautam Kumar. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : Rishabh Jindal 2
Source
https://www.geeksforgeeks.org/pairwise-swap-elements-of-a-given-linked-list-by-changing-links/
1011
Chapter 167
Partitioning a linked list around a given value and If we don’t care about making the
elements of the list ”stable” - GeeksforGeeks
Given a linked list and a value x, partition a linked list around a value x, such that all nodes
less than x come before all nodes greater than or equal to x. If x is contained within the
list the values of x only need to be after the elements less than x (see below). The partition
element x can appear anywhere in the “right partition”; it does not need to appear between
the left and right partitions.
Similar problem : Partitioning a linked list around a given value and keeping the original
order
Examples:
If we don’t care about making the elements of the list “stable” then we can instead rearrange
the elements by growing the list at the head and tail.
In this approach, we start a “new” list (using the existing nodes). Elements bigger than the
pivot element are put at the tail and elements smaller are put at the head. Each time we
insert an element, we update either the head or tail.
Below is C++ implementation of above idea.
1012
Chapter 167. Partitioning a linked list around a given value and If we don’t care about
making the elements of the list “stable”
1013
Chapter 167. Partitioning a linked list around a given value and If we don’t care about
making the elements of the list “stable”
}
tail->next = NULL;
int x = 5;
head = partition(head, x);
printList(head);
return 0;
}
Output:
1 2 2 3 5 8 10
Source
https://www.geeksforgeeks.org/partitioning-linked-list-around-given-value-dont-care-making-elements-list-stable/
1014
Chapter 168
Partitioning a linked list around a given value and keeping the original order - GeeksforGeeks
Given a linked list and a value x, partition it such that all nodes less than x come first, then
all nodes with value equal to x and finally nodes with value greater than or equal to x. The
original relative order of the nodes in each of the three partitions should be preserved. The
partition must work in-place.
Examples:
Input : 1->4->3->2->5->2->3,
x = 3
Output: 1->2->2->3->3->4->5
Input : 1->4->2->10
x = 3
Output: 1->2->4->10
Input : 10->4->20->10->3
x = 3
Output: 3->10->4->20->10
To solve this problem we can use partition method of Quick Sort but this would not
preserve the original relative order of the nodes in each of the two partitions.
Below is the algorithm to solve this problem :
• Initialize first and last nodes of below three linked lists as NULL.
1015
Chapter 168. Partitioning a linked list around a given value and keeping the original order
1016
Chapter 168. Partitioning a linked list around a given value and keeping the original order
{
// If current node is equal to x, append it
// to the list of x values
if (head->data == x)
{
if (equalHead == NULL)
equalHead = equalLast = head;
else
{
equalLast->next = head;
equalLast = equalLast->next;
}
}
head = head->next;
}
1017
Chapter 168. Partitioning a linked list around a given value and keeping the original order
if (smallerHead == NULL)
{
if (equalHead == NULL)
return greaterHead;
equalLast->next = greaterHead;
return equalHead;
}
int x = 3;
head = partition(head, x);
printList(head);
1018
Chapter 168. Partitioning a linked list around a given value and keeping the original order
return 0;
}
Output:
2 10 4 5 30 50
Source
https://www.geeksforgeeks.org/partitioning-a-linked-list-around-a-given-value-and-keeping-the-original-order/
1019
Chapter 169
Point arbit pointer to greatest value right side node in a linked list - GeeksforGeeks
Given singly linked list with every node having an additional “arbitrary” pointer that cur-
rently points to NULL. We need to make the “arbitrary” pointer to greatest value node in
a linked list on its right side.
A Simple Solution is to traverse all nodes one by one. For every node, find the node
which has greatest value on right side and change the next pointer. Time Complexity of
this solution is O(n2 ).
An Efficient Solution can work in O(n) time. Below are steps.
1020
Chapter 169. Point arbit pointer to greatest value right side node in a linked list
1021
Chapter 169. Point arbit pointer to greatest value right side node in a linked list
if (node->next)
cout << node->next->data << "\t\t";
else cout << "NULL" << "\t\t";
if (node->arbit)
cout << node->arbit->data;
else cout << "NULL";
1022
Chapter 169. Point arbit pointer to greatest value right side node in a linked list
head = populateArbit(head);
return 0;
}
Output:
Recursive Solution:
We can recursively reach the last node and traverse the linked list from end. Recursive
solution doesn’t require reversing of linked list. We can also use a stack in place of recursion
to temporarily hold nodes. Thanks to Santosh Kumar Mishra for providing this solution.
1023
Chapter 169. Point arbit pointer to greatest value right side node in a linked list
return;
}
if(node->next)
cout << node->next->data << "\t\t";
else cout << "NULL" << "\t\t";
if(node->arbit)
cout << node->arbit->data;
else cout << "NULL";
1024
Chapter 169. Point arbit pointer to greatest value right side node in a linked list
populateArbit(head);
return 0;
}
Output:
This article is contributed by Aditya Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/point-arbit-pointer-greatest-value-right-side-node-linked-list/
1025
Chapter 170
Point to next higher value node in a linked list with an arbitrary pointer - GeeksforGeeks
Given singly linked list with every node having an additional “arbitrary” pointer that cur-
rently points to NULL. Need to make the “arbitrary” pointer point to the next higher value
node.
We strongly recommend to minimize your browser and try this yourself first
A Simple Solution is to traverse all nodes one by one, for every node, find the node which
has next greater value of the current node and changes the next pointer. Time Complexity
of this solution is O(n2 ).
An Efficient Solution works in O(nLogn) time. The idea is to use Merge Sort for linked
list.
1026
Chapter 170. Point to next higher value node in a linked list with an arbitrary pointer
1) Traverse input list and copy next pointer to arbit pointer for every node.
2) Do Merge Sort for the linked list formed by arbit pointers.
Below is C implementation of the above idea. All of the merger sort functions are taken from
here. The taken functions are modified here so that they work on arbit pointers instead of
next pointers.
/* function prototypes */
struct Node* SortedMerge(struct Node* a, struct Node* b);
void FrontBackSplit(struct Node* source,
struct Node** frontRef, struct Node** backRef);
1027
Chapter 170. Point to next higher value node in a linked list with an arbitrary pointer
{
struct Node* result = NULL;
/* Base cases */
if (a == NULL)
return (b);
else if (b==NULL)
return (a);
return (result);
}
/* Split the nodes of the given list into front and back halves,
and return the two lists using the reference parameters.
If the length is odd, the extra node should go in the front list.
Uses the fast/slow pointer strategy. */
void FrontBackSplit(struct Node* source,
struct Node** frontRef, struct Node** backRef)
{
struct Node* fast, *slow;
if (source==NULL || source->arbit==NULL)
{
/* length < 2 cases */
*frontRef = source;
*backRef = NULL;
return;
}
1028
Chapter 170. Point to next higher value node in a linked list with an arbitrary pointer
{
slow = slow->arbit;
fast = fast->arbit;
}
}
new_node->arbit = NULL;
1029
Chapter 170. Point to next higher value node in a linked list with an arbitrary pointer
getchar();
return 0;
}
Output:
1030
Chapter 170. Point to next higher value node in a linked list with an arbitrary pointer
This article is contributed by Saurabh Bansal. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/point-to-next-higher-value-node-in-a-linked-list-with-an-arbitrary-pointer/
1031
Chapter 171
struct Node
{
int data;
struct Node *next;
};
fun1(head->next);
printf("%d ", head->data);
}
fun1() prints the given Linked List in reverse manner. 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 ?
1032
Chapter 171. Practice questions for Linked List and Recursion
{
if(head== NULL)
return;
printf("%d ", head->data);
if(head->next != NULL )
fun2(head->next->next);
printf("%d ", head->data);
}
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 above functions.
#include<stdio.h>
#include<stdlib.h>
fun1(head->next);
printf("%d ", head->data);
}
if(start->next != NULL )
fun2(start->next->next);
1033
Chapter 171. Practice questions for Linked List and Recursion
getchar();
return 0;
}
1034
Chapter 171. Practice questions for Linked List and Recursion
Source
https://www.geeksforgeeks.org/practice-questions-for-linked-list-and-recursion/
1035
Chapter 172
Input : 1 2 3 4 5 6
Output : 6 5 4 3 2 1
Input : 12 23 34 45 56 67 78
Output : 78 67 56 45 34 23 12
Given a Linked List, display the linked list in reverse without using recursion, stack or
modifications to given list.
Examples:
Input : 1->2->3->4->5->NULL
Output :5->4->3->2->1->NULL
Input :10->5->15->20->24->NULL
Output :24->20->15->5->10->NULL
Below are different solutions that are now allowed here as we cannot use extra space and
modify list.
1) Recursive solution to print reverse a linked list. Requires extra space.
1036
Chapter 172. Print Reverse a linked list using Stack
2) Reverse linked list and then print. This requires modifications to original list.
3) A O(n2 ) solution to print reverse of linked list that first count nodes and then prints k-th
node from end.
In this post, an efficient stack based solution is discussed.
1. First insert all the element in stack
2. Print stack till stack is not empty
Note: Instead of inserting data from each node into the stack, insert the node’s address onto
the stack. This is because the size of the node’s data will be generally more than the size
of the node’s address. Thus the stack would end up requiring more memory if it directly
stored the data elements. Also, we cannot insert the node’s data onto the stack if each node
contained more than one data member. Hence the simpler and efficient solution would be
to simply insert the node’s address.
1037
Chapter 172. Print Reverse a linked list using Stack
}
return count;
}
1038
Chapter 172. Print Reverse a linked list using Stack
printReverse(head);
return 0;
}
Output:
5 4 3 2 1
Source
https://www.geeksforgeeks.org/print-reverse-linked-list-using-stack/
1039
Chapter 173
Input : 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10
Output : 1 -> 3 -> 5 -> 7 -> 9
Input : 10 -> 9
Output : 10
Recursive Approach :
1. Initialize a static variable(say flag)
2. If flag is odd print the node
3. increase head and flag by 1, and recurse for next nodes.
C++
1040
Chapter 173. Print alternate nodes of a linked list using recursion
// Driver code
int main()
{
// Start with the empty list
struct Node* head = NULL;
push(&head, 10);
push(&head, 9);
push(&head, 8);
push(&head, 7);
push(&head, 6);
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
printAlternate(head);
return 0;
}
1041
Chapter 173. Print alternate nodes of a linked list using recursion
Output:
1 3 5 7 9
Source
https://www.geeksforgeeks.org/print-alternate-nodes-linked-list-using-recursion/
1042
Chapter 174
Algorithm
1043
Chapter 174. Print reverse of a Linked List without actually reversing
printReverse(head)
1. call print reverse for hed->next
2. print head->data
Implementation:
/*UTILITY FUNCTIONS*/
/* Push a node to linked list. Note that this function
changes the head */
void push(struct Node** head_ref, char new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
1044
Chapter 174. Print reverse of a Linked List without actually reversing
new_node->next = (*head_ref);
printReverse(head);
return 0;
}
Java
/* Utility Functions */
1045
Chapter 174. Print reverse of a Linked List without actually reversing
llist.printReverse(llist.head);
}
}
/* This code is contributed by Rajat Mishra */
Output:
4 3 2 1
Source
https://www.geeksforgeeks.org/print-reverse-of-a-linked-list-without-actually-reversing/
1046
Chapter 175
Print reverse of a Linked List without extra space and modifications - GeeksforGeeks
Given a Linked List, display the linked list in reverse without using recursion, stack or
modifications to given list.
Examples:
Input : 1->2->3->4->5->NULL
Output :5->4->3->2->1->NULL
Input :10->5->15->20->24->NULL
Output :24->20->15->5->10->NULL
Below are different solutions that are now allowed here as we cannot use extra space and
modify list.
1) Recursive solution to print reverse a linked list. Requires extra space.
2) Reverse linked list and then print. This requires modifications to original list.
3) Stack based solution to print linked list reverse. Push all nodes one by one to a stack.
Then one by one pop elements from stack and print. This also requires extra space.
Algorithms:
1047
Chapter 175. Print reverse of a Linked List without extra space and modifications
2) For i = n to 1, do following.
Print i-th node using get n-th node function
1048
Chapter 175. Print reverse of a Linked List without extra space and modifications
printReverse(head);
return 0;
}
Output:
5 4 3 2 1
Source
https://www.geeksforgeeks.org/print-reverse-linked-list-without-extra-space-modifications/
1049
Chapter 176
Approach :
1. Traverse the whole linked list.
2. Set count = 0.
3. Print node when count is even.
4. Visit the next node.
C
1050
Chapter 176. Print the alternate nodes of linked list (Iterative Method)
// Driver code
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
printAlternateNode(head);
1051
Chapter 176. Print the alternate nodes of linked list (Iterative Method)
return 0;
}
Python3
new = Node(data)
new.next = self
return new
# Driver Code
node = Node()
node.printAlternateNode()
Output :
1052
Chapter 176. Print the alternate nodes of linked list (Iterative Method)
8 11 12
Source
https://www.geeksforgeeks.org/print-alternate-nodes-linked-listiterative-method/
1053
Chapter 177
• push(): This function is used to insert a new data into the queue.
• pop(): This function removes the element with the highest priority form the queue.
• peek() / top(): This function is used to get the highest priority element in the queue
without removing it from the queue.
Priority Queues can be implemented using common data structures like arrays, linked-lists,
heaps and binary trees.
Prerequisites :
Linked Lists, Priority Queues
The list is so created so that the highest priority element is always at the head of the list.
The list is arranged in descending order of elements based on their priority. This allow us to
remove the highest priority element in O(1) time. To insert an element we must traverse the
list and find the proper position to insert the node so that the overall order of the priority
queue is maintained. This makes the push() operation takes O(N) time. The pop() and
peek() operations are performed in constant time.
Algorithm :
PUSH(HEAD, DATA, PRIORITY)
Step 1: Create new node with DATA and PRIORITY
Step 2: Check if HEAD has lower priority. If true follow Steps 3-4 and end. Else goto Step
5.
Step 3: NEW -> NEXT = HEAD
Step 4: HEAD = NEW
Step 5: Set TEMP to head of the list
1054
Chapter 177. Priority Queue using Linked List
Step 6: While TEMP -> NEXT != NULL and TEMP -> NEXT -> PRIORITY > PRI-
ORITY
Step 7: TEMP = TEMP -> NEXT
[END OF LOOP]
Step 8: NEW -> NEXT = TEMP -> NEXT
Step 9: TEMP -> NEXT = NEW
Step 10: End
POP(HEAD)
Step 2: Set the head of the list to the next node in the list. HEAD = HEAD -> NEXT.
Step 3: Free the node at the head of the list
Step 4: End
PEEK(HEAD):
Step 1: Return HEAD -> DATA
Step 2: End
Below is the implementation of the algorithm :
C
// Node
typedef struct node {
int data;
} Node;
return temp;
}
1055
Chapter 177. Priority Queue using Linked List
{
return (*head)->data;
}
1056
Chapter 177. Priority Queue using Linked List
{
return (*head) == NULL;
}
// Driver code
int main()
{
// Create a Priority Queue
// 7->4->5->6
Node* pq = newNode(4, 1);
push(&pq, 5, 2);
push(&pq, 6, 3);
push(&pq, 7, 0);
while (!isEmpty(&pq)) {
printf("%d ", peek(&pq));
pop(&pq);
}
return 0;
}
Output:
7 4 5 6
Source
https://www.geeksforgeeks.org/priority-queue-using-linked-list/
1057
Chapter 178
• push(): This function is used to insert a new data into the queue.
• pop(): This function removes the element with the lowest priority value form the
queue.
• peek() / top(): This function is used to get the lowest priority element in the queue
without removing it from the queue.
Approach :
1. Create a doubly linked list having fields info(hold the information of the Node), prior-
ity(hold the priority of the Node), prev(point to previous Node), next(point to next Node).
2. Insert the element and priority in the Node.
3. Arrange the Nodes in the increasing order of the priority.
Below is the implementation of above steps :
C++
1058
Chapter 178. Priority Queue using doubly linked list
int priority;
struct Node *prev, *next;
};
1059
Chapter 178. Priority Queue using doubly linked list
}
}
}
// Diver code
int main()
{
Node *front = NULL, *rear = NULL;
push(&front, &rear, 2, 3);
push(&front, &rear, 3, 4);
push(&front, &rear, 4, 5);
push(&front, &rear, 5, 6);
push(&front, &rear, 6, 7);
push(&front, &rear, 1, 2);
return 0;
}
Output:
1060
Chapter 178. Priority Queue using doubly linked list
1
2
Related Article :
Priority Queue using Singly Linked List
Time Complexities and Comparison with Binary Heap:
Source
https://www.geeksforgeeks.org/priority-queue-using-doubly-linked-list/
1061
Chapter 179
Program for n’th node from the end of a Linked List - GeeksforGeeks
Given a Linked List and a number n, write a function that returns the value at the n’th
node from end of the Linked List.
For example, if input is below list and n = 3, then output is “B”
/* Function to get the nth node from the last of a linked list*/
void printNthFromLast(struct Node* head, int n)
{
1062
Chapter 179. Program for n’th node from the end of a Linked List
int len = 0, i;
struct Node *temp = head;
temp = head;
return;
}
1063
Chapter 179. Program for n’th node from the end of a Linked List
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 35);
printNthFromLast(head, 4);
return 0;
}
Java
// Simple Java program to find n'th node from end of linked list
class LinkedList
{
Node head; // head of the list
temp = head;
1064
Chapter 179. Program for n’th node from the end of a Linked List
System.out.println(temp.data);
}
llist.printNthFromLast(4);
}
}// This code is contributed by Rajat Mishra
Output:
35
Following is a recursive C code for the same method. Thanks to Anuj Bansal for providing
following code.
1065
Chapter 179. Program for n’th node from the end of a Linked List
printNthFromLast(head->next, n);
if (++i == n)
printf("%d", head->data);
}
/* Function to get the nth node from the last of a linked list*/
void printNthFromLast(struct Node *head, int n)
{
struct Node *main_ptr = head;
struct Node *ref_ptr = head;
int count = 0;
if(head != NULL)
{
while( count < n )
{
if(ref_ptr == NULL)
{
printf("%d is greater than the no. of "
"nodes in list", n);
return;
}
ref_ptr = ref_ptr->next;
count++;
} /* End of while*/
1066
Chapter 179. Program for n’th node from the end of a Linked List
while(ref_ptr != NULL)
{
main_ptr = main_ptr->next;
ref_ptr = ref_ptr->next;
}
printf("Node no. %d from last is %d ",
n, main_ptr->data);
}
}
printNthFromLast(head, 4);
}
Java
// Java program to find n'th node from end using slow and
// fast pointers
class LinkedList
{
Node head; // head of the list
1067
Chapter 179. Program for n’th node from the end of a Linked List
int count = 0;
if (head != null)
{
while (count < n)
{
if (ref_ptr == null)
{
System.out.println(n+" is greater than the no "+
" of nodes in the list");
return;
}
ref_ptr = ref_ptr.next;
count++;
}
while (ref_ptr != null)
{
main_ptr = main_ptr.next;
ref_ptr = ref_ptr.next;
}
System.out.println("Node no. "+n+" from last is "+
main_ptr.data);
}
}
1068
Chapter 179. Program for n’th node from the end of a Linked List
llist.printNthFromLast(4);
}
} // This code is contributed by Rajat Mishra
Python
# Node class
class Node:
class LinkedList:
1069
Chapter 179. Program for n’th node from the end of a Linked List
ref_ptr = self.head
count = 0
if(self.head is not None):
while(count < n ):
if(ref_ptr is None):
print "%d is greater than the no. pf nodes in list" %(n)
return
ref_ptr = ref_ptr.next
count += 1
llist.printNthFromLast(4)
Output:
Source
https://www.geeksforgeeks.org/nth-node-from-the-end-of-a-linked-list/
1070
Chapter 180
A doubly linked list is a linked data structure that consists of a set of sequentially linked
records called nodes. Each node contains two fields, called links, that are references to the
previous and to the next node in the sequence of nodes.
Traversal of a doubly linked list can be in either direction. In fact, the direction of traversal
can change many times, if desired.
For example the function should return 3 for the above doubly linked list.
1) Initialize size to 0.
2) Initialize a node pointer, temp = head.
3) Do following while temp is not NULL
……a) temp = temp -> next
……b) size++;
4) Return size.
1071
Chapter 180. Program to find size of Doubly Linked List
1072
Chapter 180. Program to find size of Doubly Linked List
Output:
Source
https://www.geeksforgeeks.org/program-find-size-doubly-linked-list/
1073
Chapter 181
Input : a a b c
Output : a -1 b b
Input : a a c
Output : a -1 c
We have already discussed a Doubly linked list based approach in the previous post.
Approach-
1. Create a count array of size 26(assuming only lower case characters are present) and
initialize it with zero.
2. Create a queue of char datatype.
3. Store each character in queue and increase its frequency in the hash array.
4. For every character of stream, we check front of the queue.
5. If the frequency of character at the front of queue is one, then that will be the first
non repeating character.
6. Else if frequency is more than 1, then we pop that element.
7. If queue became empty that means there are no non repeating character so we will
print -1.
1074
Chapter 181. Queue based approach for first non-repeating character in a stream
C++
if (q.empty())
cout << -1 << " ";
}
cout << endl;
}
// Driver function
int main()
{
char str[] = "aabc";
firstnonrepeating(str);
return 0;
1075
Chapter 181. Queue based approach for first non-repeating character in a stream
Java
import java.util.LinkedList;
import java.util.Queue;
1076
Chapter 181. Queue based approach for first non-repeating character in a stream
}
System.out.println();
}
// Driver function
public static void main(String[] args)
{
String str = "aabc";
firstNonRepeating(str);
}
}
//This code is Contributed by Sumit Ghosh
Output:
a -1 b b
Source
https://www.geeksforgeeks.org/queue-based-approach-for-first-non-repeating-character-in-a-stream/
1077
Chapter 182
// The queue, front stores the front node of LL and rear stores ths
// last node of LL
struct Queue
{
struct QNode *front, *rear;
1078
Chapter 182. Queue | Set 2 (Linked List Implementation)
};
// Add the new node at the end of queue and change rear
q->rear->next = temp;
q->rear = temp;
}
1079
Chapter 182. Queue | Set 2 (Linked List Implementation)
Java
public Queue() {
1080
Chapter 182. Queue | Set 2 (Linked List Implementation)
// Add the new node at the end of queue and change rear
this.rear.next = temp;
this.rear = temp;
}
// Driver class
public class Test
{
public static void main(String[] args)
{
Queue q=new Queue();
q.enqueue(10);
1081
Chapter 182. Queue | Set 2 (Linked List Implementation)
q.enqueue(20);
q.dequeue();
q.dequeue();
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
Python3
def __init__(self):
self.front = self.rear = None
def isEmpty(self):
return self.front == None
if self.rear == None:
self.front = self.rear = temp
return
self.rear.next = temp
self.rear = temp
1082
Chapter 182. Queue | Set 2 (Linked List Implementation)
def DeQueue(self):
if self.isEmpty():
return
temp = self.front
self.front = temp.next
if(self.front == None):
self.rear = None
return str(temp.data)
# Driver Code
if __name__== '__main__':
q = Queue()
q.EnQueue(10)
q.EnQueue(20)
q.DeQueue()
q.DeQueue()
q.EnQueue(30)
q.EnQueue(40)
q.EnQueue(50)
Output:
Dequeued item is 30
Time Complexity: Time complexity of both operations enqueue() and dequeue() is O(1)
as we only change few pointers in both operations. There is no loop in any of the operations.
Source
https://www.geeksforgeeks.org/queue-set-2-linked-list-implementation/
1083
Chapter 183
/* This function takes last element as pivot, places the pivot element at its
correct position in sorted array, and places all smaller (smaller than
pivot) to left of pivot and all greater elements to right of pivot */
int partition (int arr[], int l, int h)
{
int x = arr[h];
int i = (l - 1);
/* A[] --> Array to be sorted, l --> Starting index, h --> Ending index */
void quickSort(int A[], int l, int h)
{
1084
Chapter 183. QuickSort on Doubly Linked List
if (l < h)
{
int p = partition(A, l, h); /* Partitioning index */
quickSort(A, l, p - 1);
quickSort(A, p + 1, h);
}
}
C++
1085
Chapter 183. QuickSort on Doubly Linked List
swap(&(i->data), &(j->data));
}
}
i = (i == NULL)? l : i->next; // Similar to i++
swap(&(i->data), &(h->data));
return i;
}
1086
Chapter 183. QuickSort on Doubly Linked List
1087
Chapter 183. QuickSort on Doubly Linked List
printList(a);
quickSort(a);
return 0;
}
Java
Node(int d){
data = d;
next = null;
prev = null;
}
}
1088
Chapter 183. QuickSort on Doubly Linked List
1089
Chapter 183. QuickSort on Doubly Linked List
list.push(5);
list.push(20);
list.push(4);
list.push(3);
list.push(30);
}
}
Output :
1090
Chapter 183. QuickSort on Doubly Linked List
Time Complexity: Time complexity of the above implementation is same as time com-
plexity of QuickSort() for arrays. It takes O(n^2) time in worst case and O(nLogn) in
average and best cases. The worst case occurs when the linked list is already sorted.
Can we implement random quick sort for linked list?
Quicksort can be implemented for Linked List only when we can pick a fixed point as
pivot (like last element in above implementation). Random QuickSort cannot be efficiently
implemented for Linked Lists by picking random pivot.
Exercise:
The above implementation is for doubly linked list. Modify it for singly linked list. Note
that we don’t have prev pointer in singly linked list.
Refer QuickSort on Singly Linked Listfor solution.
Source
https://www.geeksforgeeks.org/quicksort-for-linked-list/
1091
Chapter 184
1092
Chapter 184. QuickSort on Singly Linked List
new_node->data = new_data;
// During partition, both the head and end of the list might change
// which is updated in the newHead and newEnd variables
while (cur != pivot)
{
if (cur->data < pivot->data)
{
// First node that has a value less than the pivot - becomes
// the new head
if ((*newHead) == NULL)
(*newHead) = cur;
prev = cur;
cur = cur->next;
1093
Chapter 184. QuickSort on Singly Linked List
}
else // If cur node is greater than pivot
{
// Move cur node to next of tail, and change tail
if (prev)
prev->next = cur->next;
struct Node *tmp = cur->next;
cur->next = NULL;
tail->next = cur;
tail = cur;
cur = tmp;
}
}
1094
Chapter 184. QuickSort on Singly Linked List
tmp->next = NULL;
return newHead;
}
// The main function for quick sort. This is a wrapper over recursive
// function quickSortRecur()
void quickSort(struct Node **headRef)
{
(*headRef) = quickSortRecur(*headRef, getTail(*headRef));
return;
}
quickSort(&a);
return 0;
}
Output:
1095
Chapter 184. QuickSort on Singly Linked List
30 3 4 20 5
Linked List after sorting
3 4 5 20 30
Source
https://www.geeksforgeeks.org/quicksort-on-singly-linked-list/
1096
Chapter 185
Input: 1->2->3->4
Output: 1->3->2->4
Input: 11->15->20->5->10
Output: 11->20->5->15->10
A simple approach to do this, is to sort the linked list using merge sort and then swap
alternate, but that requires O(n Log n) time complexity. Here n is number of elements in
linked list.
An efficient approach which requires O(n) time is, using a single scan similar to bubble
sort and then maintain a flag for representing which order (< or >) currently we are. If the
current two elements are not in that order then swap those elements otherwise not. Please
refer this for detailed explanation of swapping order.
1097
Chapter 185. Rearrange a Linked List in Zig-Zag fashion
current = current->next;
flag = !flag; /* flip flag for reverse checking */
}
}
/* UTILITY FUNCTIONS */
/* Function to push a Node */
void push(Node** head_ref, int new_data)
{
/* allocate Node */
struct Node* new_Node = new Node;
1098
Chapter 185. Rearrange a Linked List in Zig-Zag fashion
new_Node->next = (*head_ref);
zigZagList(head);
return (0);
}
Output :
1099
Chapter 185. Rearrange a Linked List in Zig-Zag fashion
4->3->7->8->6->2->1->NULL
In above code, push function pushes the node at the front of the linked list, the code can
be easily modified for pushing node at the end of list. Other thing to note is, swapping of
data between two nodes is done by swap by value not swap by links for simplicity, for swap
by links technique please see this.
Time complexity : O(n)
Auxiliary Space : O(1)
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/linked-list-in-zig-zag-fashion/
1100
Chapter 186
Input: 1->2->3->4
Output: 1->3->2->4
Input: 11->15->20->5->10
Output: 11->20->5->15->10
Approach:
A solution that converts given list into zigzag form is discussed in previous post. The
solution discussed performs conversion by swapping data of nodes. Swapping data of nodes
may be expensive in many situations when the data contains many fields. In this post, a
solution that performs conversion by swapping links is discussed.
The idea is to traverse the given linked list and check if current node maintains the zigzag
order or not. To check if given node maintains zigzag order or not, a variable ind is used.
If ind = 0, then the current node’s data should be less than its adjacent node’s data and
if ind = 1, then current node’s data should be greater than its adjacent node’s data. If
the current node violates the zigzag order, then swap the position of both nodes. For doing
this step, maintain two pointers prev and next. prev stores previous node of current node
and next stores new next node of current node. To swap both nodes, the following steps are
performed:
• Make next node of current node, the next node of previous node.
1101
Chapter 186. Rearrange a Linked List in Zig-Zag fashion | Set-2
while (curr->next) {
1102
Chapter 186. Rearrange a Linked List in Zig-Zag fashion | Set-2
if (res == NULL)
res = curr->next;
prev = curr;
curr = curr->next;
}
return res;
}
/* UTILITY FUNCTIONS */
/* Function to push a Node */
void push(Node** head_ref, int new_data)
{
1103
Chapter 186. Rearrange a Linked List in Zig-Zag fashion | Set-2
/* allocate Node */
struct Node* new_Node = new Node;
head = zigZagList(head);
return 0;
}
1104
Chapter 186. Rearrange a Linked List in Zig-Zag fashion | Set-2
Output:
Source
https://www.geeksforgeeks.org/rearrange-a-linked-list-in-zig-zag-fashion-set-2/
1105
Chapter 187
Simple Solution
Time complexity of the above simple solution is O(n2 ) where n is the number of nodes in
the linked list.
Better Solution
1) Copy contents of given linked list to a vector.
1106
Chapter 187. Rearrange a given linked list in-place.
while (curr)
{
next = curr->next;
curr->next = prev;
1107
Chapter 187. Rearrange a given linked list in-place.
prev = curr;
curr = next;
}
*head = prev;
}
1108
Chapter 187. Rearrange a given linked list in-place.
// Driver program
int main()
{
Node *head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(5);
Java
/* Node Class */
static class Node {
1109
Chapter 187. Rearrange a given linked list in-place.
int data;
Node next;
1110
Chapter 187. Rearrange a given linked list in-place.
}
}
1111
Chapter 187. Rearrange a given linked list in-place.
Output:
struct node{
int data;
struct node *next;
};
typedef struct node Node;
// function for rearranging a linked list with high and low value.
void rearrange(Node *head)
{
if(head == NULL) //Base case.
return;
while(curr)
{
// swap function for swapping data.
if(prev -> data > curr -> data)
swap(prev -> data, curr -> data);
1112
Chapter 187. Rearrange a given linked list in-place.
// driver code
int main()
{
rearrange(head);
display(head);
return 0;
1113
Chapter 187. Rearrange a given linked list in-place.
Source
https://www.geeksforgeeks.org/rearrange-a-given-linked-list-in-place/
1114
Chapter 188
Rearrange a given list such that it consists of alternating minimum maximum elements -
GeeksforGeeks
Given a list of integers, rearrange the list such that it consists of alternating minimum
maximum elements using only list operations. The first element of the list should
be minimum and second element should be maximum of all elements present in the list.
Similarly, third element will be next minimum element and fourth element is next maximum
element and so on. Use of extra space is not permitted.
Examples:
Input: [1 3 8 2 7 5 6 4]
Output: [1 8 2 7 3 6 4 5]
Input: [1 2 3 4 5 6 7]
Output: [1 7 2 6 3 5 4]
Input: [1 6 2 5 3 4]
Output: [1 6 2 5 3 4]
The idea is to sort the list in ascending order first. Then we start popping elements from
the end of the list and insert them into their correct position in the list.
Below is C++ implementation of above idea –
C/C++
1115
Chapter 188. Rearrange a given list such that it consists of alternating minimum
maximum elements
// Driver code
int main()
{
// input list
list<int> inp({ 1, 3, 8, 2, 7, 5, 6, 4 });
return 0;
}
Java
1116
Chapter 188. Rearrange a given list such that it consists of alternating minimum
maximum elements
class AlternateSort
{
// Function to rearrange a given list such that it
// consists of alternating minimum maximum elements
// using LinkedList
public static void alternateSort(LinkedList<Integer> ll)
{
Collections.sort(ll);
System.out.println(ll);
}
Output:
1 8 2 7 3 6 4 5
Source
https://www.geeksforgeeks.org/rearrange-given-list-consists-alternating-minimum-maximum-elements/
1117
Chapter 189
Input : 1->2->3->4->5->6->7->8
Output :1->8->2->7->3->6->4->5
Input :10->11->15->13
Output :10->13->11->15
We have discussed three different solution in Rearrange a given linked list in-place.
In this post a different Deque based solution is discussed.
Method
1) Create an empty deque
2) Insert all element from the linked list to the deque
3) Insert the element back to the linked list from deque in alternate fashion i.e first then
last and so on
1118
Chapter 189. Rearrange a linked list in to alternate first and last element
};
/*UTILITY FUNCTIONS*/
/* Push a node to linked list. Note that this function
changes the head */
void push(struct Node** head_ref, char new_data)
{
/* allocate node */
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
1119
Chapter 189. Rearrange a linked list in to alternate first and last element
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
cout << "Given linked list\t";
printList(head);
arrange(head);
cout << "\nAfter rearrangement\t";
printList(head);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/rearrange-linked-list-alternate-first-last-element/
1120
Chapter 190
Rearrange a linked list such that all even and odd positioned nodes are together - Geeks-
forGeeks
Rearrange a linked list in such a way that all odd position nodes are together and all even
positions node are together,
Examples:
Input: 1->2->3->4
Output: 1->3->2->4
Input: 10->22->30->43->56->70
Output: 10->30->56->22->43->70
The important thing in this question is to make sure that all below cases are handled
1) Empty linked list
2) A linked list with only one node
3) A linked list with only two nodes
4) A linked list with odd number of nodes
5) A linked list with even number of nodes
The below program maintains two pointers ‘odd’ and ‘even’ for current nodes at odd an
even positions respectively. We also store first node of even linked list so that we can attach
the even list at the end of odd list after all odd and even nodes are connected together in
two different lists.
1121
Chapter 190. Rearrange a linked list such that all even and odd positioned nodes are
together
while (1)
{
// If there are no more nodes, then connect
// first node of even list to the last node
// of odd list
if (!odd || !even || !(even->next))
{
odd->next = evenFirst;
1122
Chapter 190. Rearrange a linked list such that all even and odd positioned nodes are
together
break;
}
return head;
}
// Driver code
int main(void)
{
Node *head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(5);
head = rearrangeEvenOdd(head);
1123
Chapter 190. Rearrange a linked list such that all even and odd positioned nodes are
together
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/rearrange-a-linked-list-such-that-all-even-and-odd-positioned-nodes-are-together/
1124
Chapter 191
Recursive Approach to find nth node from the end in the linked list - GeeksforGeeks
Find the nth node from the end in the given linked list using a recursive approach.
Examples:
Algorithm:
findNthFromLastUtil(head, n)
Initialize nth_last = NULL
Initialize count = 0
1125
Chapter 191. Recursive Approach to find nth node from the end in the linked list
// put in data
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// recursive call
findNthFromLast(head->next, n, count, nth_last);
// increment count
1126
Chapter 191. Recursive Approach to find nth node from the end in the linked list
*count = *count + 1;
int n = 2;
findNthFromLastUtil(head, n);
return 0;
}
Java
// Java implementation to recursively
// find the nth node from the last
// of the linked list
import java.util.*;
1127
Chapter 191. Recursive Approach to find nth node from the end in the linked list
class GFG
{
static int count = 0, data = 0;
// a node of a linked list
static class Node
{
int data;
Node next;
}
// function to get a new node
static Node getNode(int data)
{
// allocate space
Node newNode = new Node();
// put in data
newNode.data = data;
newNode.next = null;
return newNode;
}
// funnction to recursively
// find the nth node from
// the last of the linked list
static void findNthFromLast(Node head, int n,
Node nth_last)
{
// if list is empty
if (head == null)
return;
// recursive call
findNthFromLast(head.next, n, nth_last);
// increment count
count = count + 1;
// if true, then head is the
// nth node from the last
if (count == n)
{
data = head.data;
}
}
// utility function to find
// the nth node from the last
// of the linked list
static void findNthFromLastUtil(Node head, int n)
{
1128
Chapter 191. Recursive Approach to find nth node from the end in the linked list
// Initialize
Node nth_last = new Node();
count = 0;
// find nth node from the last
findNthFromLast(head, n, nth_last);
// if node exists, then print it
if (nth_last != null)
System.out.println(“Nth node from last is: ” +
data);
else
System.out.println(“Node does not exists”);
}
// Driver Code
public static void main(String args[])
{
// linked list: 4.2.1.5.3
Node head = getNode(4);
head.next = getNode(2);
head.next.next = getNode(1);
head.next.next.next = getNode(5);
head.next.next.next.next = getNode(3);
int n = 2;
findNthFromLastUtil(head, n);
}
}
// This code is contributed
// by Arnab Kundu
Output:
Time Complexity: O(n), where ‘n’ is the number of nodes in the linked list.
Improved By : andrew1234
Source
https://www.geeksforgeeks.org/recursive-approach-to-find-nth-node-from-the-end-in-the-linked-list/
1129
Chapter 192
Input : 1 2 3 4 5 6 7
Output : 1 3 5 7
2 4 6
Input : 1 4 5 6
Output : 1 5
4 6
// Node structure
struct Node {
int data;
struct Node* next;
};
1130
Chapter 192. Recursive approach for alternating split of Linked List
if (a->next != NULL)
a->next = a->next->next;
if (b->next != NULL)
b->next = b->next->next;
moveNode(a->next, b->next);
}
1131
Chapter 192. Recursive approach for alternating split of Linked List
// Driver code
int main()
{
Node* head = NULL;
Node *a = NULL, *b = NULL;
push(&head, 7);
push(&head, 6);
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
printf("a : ");
display(a);
printf("\nb : ");
display(b);
return 0;
}
Output:
a : 1 3 5 7
b : 2 4 6
Source
https://www.geeksforgeeks.org/recursive-approach-alternating-split-linked-list/
1132
Chapter 193
We recursively reduce value of k. When k reaches 1, we delete current node and return next
of current node as new node. When function returns, we link the returned node as next of
previous node.
struct Node {
int data;
struct Node* next;
};
1133
Chapter 193. Recursive function to delete k-th node from linked list
1134
Chapter 193. Recursive function to delete k-th node from linked list
12->15->10->11->5->6->2->3 */
push(&head,3);
push(&head,2);
push(&head,6);
push(&head,5);
push(&head,11);
push(&head,10);
push(&head,15);
push(&head,12);
int k = 3;
head = deleteNode(head, k);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/recursive-function-delete-k-th-node-linked-list/
1135
Chapter 194
1136
Chapter 194. Recursive insertion and traversal linked list
traverse(head->next);
}
Complete Program:
Below is complete program to demonstrate working of insert and traverse a linked list.
1137
Chapter 194. Recursive insertion and traversal linked list
traverse(head->next);
}
// Driver code
int main()
{
Node* head = NULL;
head = insertEnd(head, 6);
head = insertEnd(head, 8);
head = insertEnd(head, 10);
head = insertEnd(head, 12);
head = insertEnd(head, 14);
traverse(head);
}
Output:
6 8 10 12 14
Source
https://www.geeksforgeeks.org/recursive-insertion-and-traversal-linked-list/
1138
Chapter 195
Recursive selection sort for singly linked list | Swapping node links - GeeksforGeeks
Given a singly linked list containing n nodes. The problem is to sort the list using recursive
selection sort technique. The approach should be such that it involves swapping node links
instead of swapping nodes data.
Examples:
In Selection Sort, we first find minimum element, swap it with the beginning node and recur
for remaining list. Below is recursive implementation of these steps for linked list.
recurSelectionSort(head)
if head->next == NULL
return head
Initialize min = head
Initialize beforeMin = NULL
Initialize ptr = head
1139
Chapter 195. Recursive selection sort for singly linked list | Swapping node links
ptr = ptr->next
if min != head
swapNodes(&head, head, min, beforeMin)
head->next = recurSelectionSort(head->next)
return head
// adjust links
prevY->next = currX;
1140
Chapter 195. Recursive selection sort for singly linked list | Swapping node links
return head;
}
1141
Chapter 195. Recursive selection sort for singly linked list | Swapping node links
1142
Chapter 195. Recursive selection sort for singly linked list | Swapping node links
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/recursive-selection-sort-singly-linked-list-swapping-node-links/
1143
Chapter 196
Input : NULL
Output : NULL
Input : 1->NULL
Output : 1->NULL
We have discussed an iterative and two recursive approaches in previous post on reverse a
linked list.
In this approach of reversing a linked list by passing a single pointer what we are trying to
do is that we are making the previous node of the current node as his next node to reverse
the linked list.
1144
Chapter 196. Recursively Reversing a linked list (A simple implementation)
1. We return the pointer of next node to his previous(current) node and then make the
previous node as the next node of returned node and then returning the current node.
2. We first traverse till the last node and making the last node as the head node of
reversed linked list and then applying the above procedure in the recursive manner.
struct LinkedList {
Node* head;
LinkedList()
{
head = NULL;
}
1145
Chapter 196. Recursively Reversing a linked list (A simple implementation)
ll.reverse(ll.head);
Output:
Source
https://www.geeksforgeeks.org/recursively-reversing-a-linked-list-a-simple-implementation/
1146
Chapter 197
Input : 23->28->28->35->49->49->53->53
Output : 23->35
Input : 11->11->11->11->75->75
Output : empty List
Note that this is different from Remove Duplicates From Linked List
The idea is to maintain a pointer (prev) to the node which just previous to the block of
nodes we are checking for duplicates. In the first example, the pointer prev would point to
23 while we check for duplicates for the node 28. Once we reach the last duplicate node
with value 28 (name it current pointer), we can make the next field of prev node to be the
next of current and update current=current.next. This would delete the block of nodes with
value 28 which has duplicates.
C++
1147
Chapter 197. Remove all occurrences of duplicates from a sorted Linked List
#include <bits/stdc++.h>
using namespace std;
// Utility function
// to create a new Node
struct Node *newNode(int data)
{
Node *temp = new Node;
temp -> data = data;
temp -> next = NULL;
return temp;
}
1148
Chapter 197. Remove all occurrences of duplicates from a sorted Linked List
while(current != NULL)
{
// Until the current and
// previous values are
// same, keep updating current
while(current -> next != NULL &&
prev -> next -> data == current -> next -> data)
current = current -> next;
// Driver Code
int main()
{
// 23->28->28->35->49->49->53->53
struct Node* start = newNode(23);
start -> next = newNode(28);
start -> next -> next = newNode(28);
start -> next ->
next -> next = newNode(35);
start -> next ->
next -> next -> next = newNode(49);
start -> next ->
1149
Chapter 197. Remove all occurrences of duplicates from a sorted Linked List
removeAllDuplicates(start);
Java
1150
Chapter 197. Remove all occurrences of duplicates from a sorted Linked List
current = current.next;
}
1151
Chapter 197. Remove all occurrences of duplicates from a sorted Linked List
ll.removeAllDuplicates();
Output:
1152
Chapter 197. Remove all occurrences of duplicates from a sorted Linked List
Source
https://www.geeksforgeeks.org/remove-occurrences-duplicates-sorted-linked-list/
1153
Chapter 198
Algorithm:
removeDuplicates(head_ref, x)
if head_ref == NULL
return
Initialize current = head_ref
while current->next != NULL
if current->data == current->next->data
deleteNode(head_ref, current->next)
else
current = current->next
The algorithm for deleteNode(head_ref, current) (which deletes the node using the
pointer to the node) is discussed in this post.
1154
Chapter 198. Remove duplicates from a sorted doubly linked list
1155
Chapter 198. Remove duplicates from a sorted doubly linked list
1156
Chapter 198. Remove duplicates from a sorted doubly linked list
return 0;
}
Output:
1157
Chapter 198. Remove duplicates from a sorted doubly linked list
Source
https://www.geeksforgeeks.org/remove-duplicates-sorted-doubly-linked-list/
1158
Chapter 199
1159
Chapter 199. Remove duplicates from a sorted linked list
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging of the linked list */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
1160
Chapter 199. Remove duplicates from a sorted linked list
return 0;
}
Java
1161
Chapter 199. Remove duplicates from a sorted linked list
Node next;
Node(int d) {data = d; next = null; }
}
void removeDuplicates()
{
/*Another reference to head*/
Node current = head;
/* Utility functions */
1162
Chapter 199. Remove duplicates from a sorted linked list
{
Node temp = head;
while (temp != null)
{
System.out.print(temp.data+" ");
temp = temp.next;
}
System.out.println();
}
llist.removeDuplicates();
Output:
Time Complexity: O(n) where n is number of nodes in the given linked list.
Recursive Approach :
1163
Chapter 199. Remove duplicates from a sorted linked list
struct Node
{
int data;
struct Node* next;
};
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging of the linked list */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
1164
Chapter 199. Remove duplicates from a sorted linked list
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
return 0;
}
/* This code is contributed by Yogesh shukla */
output
Related Article :
Remove all occurrences of duplicates from a sorted Linked List
References:
cslibrary.stanford.edu/105/LinkedListProblems.pdf
Improved By : Yogesh Shukla 1
Source
https://www.geeksforgeeks.org/remove-duplicates-from-a-sorted-linked-list/
1165
Chapter 200
1166
Chapter 200. Remove duplicates from a sorted linked list using recursion
return head;
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at
the beginning of the linked list */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node = new Node;
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
1167
Chapter 200. Remove duplicates from a sorted linked list using recursion
push(&head, 13);
push(&head, 13);
push(&head, 11);
push(&head, 11);
push(&head, 11);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/remove-duplicates-sorted-linked-list-using-recursion/
1168
Chapter 201
1169
Chapter 201. Remove duplicates from an unsorted doubly linked list
1170
Chapter 201. Remove duplicates from an unsorted doubly linked list
// update 'ptr2'
ptr2 = next;
}
1171
Chapter 201. Remove duplicates from an unsorted doubly linked list
return 0;
}
Output:
1172
Chapter 201. Remove duplicates from an unsorted doubly linked list
1. Sort the elements of the doubly linked list using Merge Sort. Refer this post.
2. Remove duplicates in linear time using the algorithm to remove duplicates from a
sorted doubly linked list.
1173
Chapter 201. Remove duplicates from an unsorted doubly linked list
// update 'current'
current = next;
}
else {
1174
Chapter 201. Remove duplicates from an unsorted doubly linked list
1175
Chapter 201. Remove duplicates from an unsorted doubly linked list
// 8<->4<->4<->6<->4<->8<->4<->10<->12<->12
push(&head, 12);
push(&head, 12);
push(&head, 10);
push(&head, 4);
push(&head, 8);
push(&head, 4);
push(&head, 6);
push(&head, 4);
push(&head, 4);
push(&head, 8);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/remove-duplicates-unsorted-doubly-linked-list/
1176
Chapter 202
1177
Chapter 202. Remove duplicates from an unsorted linked list
temp->data = data;
temp->next = NULL;
return temp;
}
1178
Chapter 202. Remove duplicates from an unsorted linked list
{
/* The constructed linked list is:
10->12->11->11->12->11->10*/
struct Node *start = newNode(10);
start->next = newNode(12);
start->next->next = newNode(11);
start->next->next->next = newNode(11);
start->next->next->next->next = newNode(12);
start->next->next->next->next->next =
newNode(11);
start->next->next->next->next->next->next =
newNode(10);
removeDuplicates(start);
return 0;
}
Java
class LinkedList {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
1179
Chapter 202. Remove duplicates from an unsorted linked list
ptr1 = head;
list.remove_duplicates();
System.out.println("");
System.out.println("Linked List after removing duplicates : \n ");
1180
Chapter 202. Remove duplicates from an unsorted linked list
list.printList(head);
}
}
// This code has been contributed by Mayank Jaiswal
Output :
Please note that this method doesn’t preserve the original order of elements.
Time Complexity: O(nLogn)
METHOD 3 (Use Hashing)
We traverse the link list from head to end. For every newly encountered element, we check
whether it is in the hash table: if yes, we remove it; otherwise we put it in the hash table.
C++
1181
Chapter 202. Remove duplicates from an unsorted linked list
return temp;
}
1182
Chapter 202. Remove duplicates from an unsorted linked list
start->next->next->next = newNode(11);
start->next->next->next->next = newNode(12);
start->next->next->next->next->next =
newNode(11);
start->next->next->next->next->next->next =
newNode(10);
removeDuplicates(start);
return 0;
}
Java
import java.util.HashSet;
1183
Chapter 202. Remove duplicates from an unsorted linked list
removeDuplicate(start);
1184
Chapter 202. Remove duplicates from an unsorted linked list
Output :
Source
https://www.geeksforgeeks.org/remove-duplicates-from-an-unsorted-linked-list/
1185
Chapter 203
Input : 1->2->3->4->5->6->7->8
k = 3
Output : 1->2->4->5->7->8
As 3 is the k-th node after its deletion list
would be 1->2->4->5->6->7->8
And now 4 is the starting node then from it, 6
would be the k-th node. So no other kth node
could be there.So, final list is:
1->2->4->5->7->8.
Input: 1->2->3->4->5->6
k = 1
Output: Empty list
All nodes need to be deleted
The idea is traverse the list from beginning and keep track of nodes visited after last deletion.
Whenever count becomes k, delete current node and reset count as 0.
1186
Chapter 203. Remove every k-th node of the linked list
node is to be deleted.
(i) Delete current node i.e. do
1187
Chapter 203. Remove every k-th node of the linked list
if (k == 1)
{
freeList(head);
return NULL;
}
ptr = prev->next;
}
return head;
}
1188
Chapter 203. Remove every k-th node of the linked list
cout<<temp->data<<" ";
temp = temp->next;
}
}
int k = 3;
head = deleteKthNode(head, k);
displayList(head);
return 0;
}
Output:
1 2 4 5 7 8
Source
https://www.geeksforgeeks.org/remove-every-k-th-node-linked-list/
1189
Chapter 204
Input : 1 3 1 4 4 2 1
Output : 1 3 5 4 6 2 7
Replace 2nd occurrence of 1 with 5 i.e. (4+1)
2nd occurrence of 4 with 6 i.e. (4+2)
3rd occurrence of 1 with 7 i.e. (4+3)
Input : 1 1 1 4 3 2 2
Output : 1 5 6 4 3 2 7
Approach :
1. Traverse the linked list, store the frequencies of every number present in linked list in a
map and alongwith it find the maximum integer present in linked list i.e. maxNum.
2. Now, traverse the linked list again and if the frequency of any number is more than 1,
set its value to -1 in map on its first occurrence.
3.The reason for this is that on next occurrence of this number we will find its value -1 which
means this number has occurred before, change its data with maxNum + 1 and increment
maxNum.
Below is the implementation of idea.
1190
Chapter 204. Replace nodes with duplicates in linked list
1191
Chapter 204. Replace nodes with duplicates in linked list
if (mymap[head->data] > 1)
mymap[head->data] = -1;
head = head->next;
}
}
replaceDuplicates(head);
1192
Chapter 204. Replace nodes with duplicates in linked list
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/replace-nodes-duplicates-linked-list/
1193
Chapter 205
Here is a simple method for reversing a Doubly Linked List. All we need to do is swap prev
and next pointers for all nodes, change prev of the head (or start) and change the head
pointer in the end.
C
1194
Chapter 205. Reverse a Doubly Linked List
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging of the Doubly Linked List */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
1195
Chapter 205. Reverse a Doubly Linked List
getchar();
1196
Chapter 205. Reverse a Doubly Linked List
Java
class LinkedList {
int data;
Node next, prev;
Node(int d) {
data = d;
next = prev = null;
}
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging of the Doubly Linked List */
void push(int new_data) {
/* allocate node */
Node new_node = new Node(new_data);
1197
Chapter 205. Reverse a Doubly Linked List
list.reverse();
System.out.println("");
System.out.println("The reversed Linked List is ");
list.printList(head);
}
}
Python
1198
Chapter 205. Reverse a Doubly Linked List
class DoublyLinkedList:
# Constructor for empty Doubly Linked List
def __init__(self):
self.head = None
# 1. Allocates node
# 2. Put the data in it
new_node = Node(new_data)
1199
Chapter 205. Reverse a Doubly Linked List
self.head.prev = new_node
Source
https://www.geeksforgeeks.org/reverse-a-doubly-linked-list/
1200
Chapter 206
We have discussed at three methods to reverse a doubly linked list: Reverse a doubly linked
list, Reverse a Doubly Linked List (Set 2) and Reverse a Doubly linked list using recursion.
The first two methods work in O(n) time and require no extra space. The first method
works by swapping the next and previous pointers of each node. The second method takes
each node from the list and adds it to the beginning of the list.
There is another approach that is a bit more intuitive, but also a bit more costly.
This method is similar to reverse an array. To reverse an array, we put two pointers-one at
the beginning and another at the end of the list. We then swap the data of the two pointers
and advance both pointers toward each other. We stop either when the two pointers meet
or when they cross each other. We perform exactly n/2 swaps, and the time complexity is
also O(N).
A doubly linked list has both a previous and a next pointer, which means we can traverse in
both forward and backward directions in the list. So if we put a pointer( say left pointer),
at the beginning of the list and another right pointer at the end of the list, we can move
these pointers toward each other by advancing left pointer and receding the right pointer.
1201
Chapter 206. Reverse a Doubly Linked List | Set 4 (Swapping Data)
Algorithm
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node *prev, *next;
};
1202
Chapter 206. Reverse a Doubly Linked List | Set 4 (Swapping Data)
// Driver code
int main()
{
Node* head = newNode(5);
insert(&head, 4);
insert(&head, 3);
insert(&head, 2);
insert(&head, 1);
printList(head);
cout << "List After Reversing" << endl;
1203
Chapter 206. Reverse a Doubly Linked List | Set 4 (Swapping Data)
reverseList(&head);
printList(head);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/reverse-doubly-linked-list-set-4-swapping-data/
1204
Chapter 207
Approach: In the previous post, doubly linked list is being reversed by swapping prev and
next pointers for all nodes, changing prev of the head (or start) and then changing the head
1205
Chapter 207. Reverse a Doubly Linked List | Set-2
pointer in the end. In this post, we create a push function that adds the given node at the
beginning of the given list. We traverse the original list and one by one pass the current
node pointer to the push function. This process will reverse the list. Finally return the new
head of this reversed list.
1206
Chapter 207. Reverse a Doubly Linked List | Set-2
// update 'curr'
curr = next;
}
// update 'head_ref'
*head_ref = new_head;
}
1207
Chapter 207. Reverse a Doubly Linked List | Set-2
push(&head, getNode(10));
return 0;
}
Output:
Original list: 10 8 4 2
Reversed list: 2 4 8 10
Source
https://www.geeksforgeeks.org/reverse-doubly-linked-list-set-2/
1208
Chapter 208
We have discussed
Iterative solution to reverse a Doubly Linked List
Algorithm
1) If list is empty, return
2) Reverse head by swapping head->prev and head->next
3) If prev = NULL it means that list is fully reversed. Else reverse(head->prev)
1209
Chapter 208. Reverse a Doubly linked list using recursion
1210
Chapter 208. Reverse a Doubly linked list using recursion
Output:
Original list: 10 8 4 2
Reversed list: 2 4 8 10
1211
Chapter 208. Reverse a Doubly linked list using recursion
Source
https://www.geeksforgeeks.org/reverse-doubly-linked-list-using-recursion/
1212
Chapter 209
Examples:
Input : 1 2 3 4 5 6 (n is even)
Output : 3 2 1 6 5 4
Input : 1 2 3 4 5 6 7 (n is odd)
Output : 3 2 1 4 7 6 5
Approach: The idea is similar to Reversing a linked list in groups of size k where k is n/2.
Just need to check for mid node.
• If n is even, divide the linked list into two parts i.e. first n/2 elements and last n/2
elements and reverse both the parts.
• If n is odd, divide the linked list into three parts i.e. first n/2 elements, (n/2 + 1) th
element and last n/2 elements and reverse both the parts except (n/2 + 1) th element
.
1213
Chapter 209. Reverse a Linked List according to its Size
struct Node {
int data;
Node* next;
};
// Prints a list.
void printList(Node* head)
{
Node *temp = head;
while (temp) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
1214
Chapter 209. Reverse a Linked List according to its Size
int count = 0;
Node* curr = head;
Node* prev = NULL;
Node* next;
else {
1215
Chapter 209. Reverse a Linked List according to its Size
// to be skipped.
else
return reverseSizeBy2Util(head, n/2, true);
}
// Drivers code
int main()
{
/* Start with the empty list */
Node* head = NULL;
return 0;
}
Output:
Original List : 1 2 3 4 5 6 7 8 9
Reversed List : 4 3 2 1 5 9 8 7 6
Source
https://www.geeksforgeeks.org/reverse-a-linked-list-according-to-its-size/
1216
Chapter 210
Example:
Inputs: 1->2->3->4->5->6->7->8->NULL and k = 3
Output: 3->2->1->6->5->4->8->7->NULL.
Algorithm: reverse(head, k)
1) Reverse the first sub-list of size k. While reversing keep track of the next node and
previous node. Let the pointer to the next node be next and pointer to the previous node
be prev. See this post for reversing a linked list.
2) head->next = reverse(next, k) /* Recursively call for rest of the list and link the two
sub-lists */
3) return prev /* prev becomes the new head of the list (see the diagrams of iterative method
of this post) */
C/C++
1217
Chapter 210. Reverse a Linked List in groups of given size | Set 1
struct Node
{
int data;
struct Node* next;
};
/* UTILITY FUNCTIONS */
/* Function to push a node */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
1218
Chapter 210. Reverse a Linked List in groups of given size | Set 1
return(0);
}
Java
1219
Chapter 210. Reverse a Linked List in groups of given size | Set 1
int count = 0;
/* Utility functions */
1220
Chapter 210. Reverse a Linked List in groups of given size | Set 1
System.out.println("Reversed list");
llist.printList();
}
}
/* This code is contributed by Rajat Mishra */
Python
1221
Chapter 210. Reverse a Linked List in groups of given size | Set 1
# Node class
class Node:
class LinkedList:
1222
Chapter 210. Reverse a Linked List in groups of given size | Set 1
temp = self.head
while(temp):
print temp.data,
temp = temp.next
# Driver program
llist = LinkedList()
llist.push(9)
llist.push(8)
llist.push(7)
llist.push(6)
llist.push(5)
llist.push(4)
llist.push(3)
llist.push(2)
llist.push(1)
Output:
Time Complexity: O(n) where n is the number of nodes in the given list.
Source
https://www.geeksforgeeks.org/reverse-a-list-in-groups-of-given-size/
1223
Chapter 211
1224
Chapter 211. Reverse a Linked List in groups of given size | Set 2
struct Node {
int data;
struct Node* next;
};
return head;
}
/* UTILITY FUNCTIONS */
1225
Chapter 211. Reverse a Linked List in groups of given size | Set 2
1226
Chapter 211. Reverse a Linked List in groups of given size | Set 2
printList(head);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/reverse-linked-list-groups-given-size-set-2/
1227
Chapter 212
OUTPUT:
Approach: The approach is same as followed in reversing a singly linked list. Only here
we have to make one more adjustment by linking the last node of the reversed list to the
first node.
1228
Chapter 212. Reverse a circular linked list
#include <bits/stdc++.h>
1229
Chapter 212. Reverse a circular linked list
reverse(&head);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/reverse-circular-linked-list/
1230
Chapter 213
Output:
Algorithm:
1231
Chapter 213. Reverse a doubly circular linked list
insertEnd(head, new_node)
Declare last
last = head->prev
new_node->next = head
head->prev = new_node
new_node->prev = last
last->next = new_node
reverse(head)
Initialize new_head = NULL
Declare last
last = head->prev
Initialize curr = last, prev
return new_head
1232
Chapter 213. Reverse a doubly circular linked list
1233
Chapter 213. Reverse a doubly circular linked list
1234
Chapter 213. Reverse a doubly circular linked list
int main()
{
Node* head = NULL;
insertEnd(&head, getNode(1));
insertEnd(&head, getNode(2));
insertEnd(&head, getNode(3));
insertEnd(&head, getNode(4));
insertEnd(&head, getNode(5));
head = reverse(head);
return 0;
}
Output:
Current list:
Forward direction: 1 2 3 4 5
Backward direction: 5 4 3 2 1
Reversed list:
Forward direction: 5 4 3 2 1
Backward direction: 1 2 3 4 5
Source
https://www.geeksforgeeks.org/reverse-a-doubly-circular-linked-list/
1235
Chapter 214
1236
Chapter 214. Reverse a doubly linked list in groups of given size
1237
Chapter 214. Reverse a doubly linked list in groups of given size
int k = 2;
1238
Chapter 214. Reverse a doubly linked list in groups of given size
return 0;
}
Output:
Original list: 10 8 4 2
Modified list: 8 10 2 4
Source
https://www.geeksforgeeks.org/reverse-doubly-linked-list-groups-given-size/
1239
Chapter 215
Input : NULL
Output : NULL
Input : 1->NULL
Output : 1->NULL
Iterative Method
1. Initialize three pointers prev as NULL, curr as head and next as NULL.
2. Iterate trough the linked list. In loop, do following.
// Before changing next of current,
// store next node
next = curr->next
1240
Chapter 215. Reverse a linked list
C++
1241
Chapter 215. Reverse a linked list
// a linked list
#include<iostream>
using namespace std;
struct LinkedList
{
Node *head;
LinkedList()
{
head = NULL;
}
1242
Chapter 215. Reverse a linked list
ll.reverse();
1243
Chapter 215. Reverse a linked list
{
int data;
struct Node* next;
};
1244
Chapter 215. Reverse a linked list
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 85);
Java
class LinkedList {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
1245
Chapter 215. Reverse a linked list
node = prev;
return node;
}
Python
# Node class
class Node:
class LinkedList:
1246
Chapter 215. Reverse a linked list
def __init__(self):
self.head = None
1247
Chapter 215. Reverse a linked list
1) Divide the list in two parts - first node and rest of the linked list.
2) Call reverse for the rest of the linked list.
3) Link rest to first.
4) Fix head pointer
/* empty list */
if (*head_ref == NULL)
return;
1248
Chapter 215. Reverse a linked list
/* reverse the rest list and put the first element at the end */
recursiveReverse(&rest);
first->next->next = first;
C++
struct Node
{
int data;
struct Node *next;
};
1249
Chapter 215. Reverse a linked list
1250
Chapter 215. Reverse a linked list
head1->next = newNode(2);
head1->next->next = newNode(3);
head1->next->next->next = newNode(4);
head1->next->next->next->next = newNode(5);
head1->next->next->next->next->next = newNode(6);
head1->next->next->next->next->next->next = newNode(7);
head1->next->next->next->next->next->next->next = newNode(8);
cout << "Given linked list\n";
printlist(head1);
reverse(&head1);
cout << "\nReversed linked list\n";
printlist(head1);
return 0;
}
Java
class LinkedList {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
return head;
}
1251
Chapter 215. Reverse a linked list
reverseUtil(next1, curr);
return head;
}
Python
# Node class
1252
Chapter 215. Reverse a linked list
class Node:
class LinkedList:
self.reverseUtil(next, curr)
1253
Chapter 215. Reverse a linked list
def printList(self):
temp = self.head
while(temp):
print temp.data,
temp = temp.next
# Driver program
llist = LinkedList()
llist.push(8)
llist.push(7)
llist.push(6)
llist.push(5)
llist.push(4)
llist.push(3)
llist.push(2)
llist.push(1)
llist.reverse()
Output:
1254
Chapter 215. Reverse a linked list
Source
https://www.geeksforgeeks.org/reverse-a-linked-list/
1255
Chapter 216
Input : 1->2->3->4
Output : 4->3->2->1
Input : 6->5->4
Output : 4->5->6
C++
1256
Chapter 216. Reverse a stack without using extra space in O(n)
class StackNode {
public:
int data;
StackNode *next;
StackNode(int data)
{
this->data = data;
this->next = NULL;
}
};
class Stack {
StackNode *top;
public:
StackNode* pop()
{
StackNode *s = top;
top = top->next;
return s;
}
1257
Chapter 216. Reverse a stack without using extra space in O(n)
succ = cur->next;
cur->next = prev;
prev = cur;
cur = succ;
}
top = prev;
}
};
// driver code
int main()
{
Stack *s = new Stack();
s->push(1);
s->push(2);
s->push(3);
s->push(4);
cout << "Original Stack" << endl;;
s->display();
cout << endl;
// reverse
s->reverse();
return 0;
}
// This code is contribute by Chhavi.
Java
1258
Chapter 216. Reverse a stack without using extra space in O(n)
class StackNode {
int data;
StackNode next;
public StackNode(int data)
{
this.data = data;
this.next = null;
}
}
class Stack {
StackNode top;
1259
Chapter 216. Reverse a stack without using extra space in O(n)
cur = cur.next;
prev.next = null;
while (cur != null) {
succ = cur.next;
cur.next = prev;
prev = cur;
cur = succ;
}
this.top = prev;
}
}
// reverse
s.reverse();
System.out.println("Reversed Stack");
s.display();
}
}
Output:
Original Stack
4 3 2 1
Reversed Stack
1 2 3 4
Source
https://www.geeksforgeeks.org/reverse-stack-without-using-extra-space/
1260
Chapter 217
Input : 10->20->30->40->50->60->70->NULL
m = 3, n = 6
Output : 10->20->60->50->40->30->70->NULL
Input : 1->2->3->4->5->6->NULL
m = 2, n = 4
Output : 1->4->3->2->5->6->NULL
To reverse the linked list from position m to n, we find addresses of start and end position
of the linked list by running a loop, and then we unlink this part from the rest of the list
and then use the normal linked list reverse function which we have earlier used for reversing
the complete linked list, and use it to reverse the portion of the linked list which need to be
reversed. After reversal, we again attach the portion reversed to the main list.
1261
Chapter 217. Reverse a sublist of linked list
while (curr) {
struct Node* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
if (i == m)
revs = curr;
if (i == n) {
revend = curr;
revend_next = curr->next;
}
1262
Chapter 217. Reverse a sublist of linked list
curr = curr->next;
i++;
}
revend->next = NULL;
revs->next = revend_next;
return head;
}
// Driver code
int main()
{
struct Node* head = NULL;
push(&head, 70);
push(&head, 60);
push(&head, 50);
push(&head, 40);
1263
Chapter 217. Reverse a sublist of linked list
push(&head, 30);
push(&head, 20);
push(&head, 10);
reverseBetween(head, 3, 6);
print(head);
return 0;
}
Output:
10 20 60 50 40 30 70
Source
https://www.geeksforgeeks.org/reverse-sublist-linked-list/
1264
Chapter 218
Example:
Inputs: 1->2->3->4->5->6->7->8->9->NULL and k = 3
Output: 3->2->1->4->5->6->9->8->7->NULL.
Method 1 (Process 2k nodes and recursively call for rest of the list)
This method is basically an extension of the method discussed in thispost.
#include<stdio.h>
#include<stdlib.h>
1265
Chapter 218. Reverse alternate K nodes in a Singly Linked List
struct Node
{
int data;
struct Node* next;
};
1266
Chapter 218. Reverse alternate K nodes in a Singly Linked List
/* UTILITY FUNCTIONS */
/* Function to push a node */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
getchar();
1267
Chapter 218. Reverse alternate K nodes in a Singly Linked List
return(0);
}
Java
class LinkedList {
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
1268
Chapter 218. Reverse alternate K nodes in a Singly Linked List
current = current.next;
count++;
}
}
}
Output:
Given linked list
1269
Chapter 218. Reverse alternate K nodes in a Singly Linked List
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Modified Linked list
3 2 1 4 5 6 9 8 7 10 11 12 15 14 13 16 17 18 20 19
Time Complexity: O(n)
Source
https://www.geeksforgeeks.org/reverse-alternate-k-nodes-in-a-singly-linked-list/
1270
Chapter 219
Using a loop iterate the list till null and take string from each node and reverse the string.
1271
Chapter 219. Reverse each word in a linked list node
{
Node* temp = new Node;
temp->c = c;
temp->next = NULL;
return temp;
};
// Driver program
int main()
{
Node* head = newNode("Geeksforgeeks");
head->next = newNode("a");
head->next->next = newNode("computer");
head->next->next->next = newNode("science");
head->next->next->next->next = newNode("portal");
head->next->next->next->next->next = newNode("for");
head->next->next->next->next->next->next = newNode("geeks");
1272
Chapter 219. Reverse each word in a linked list node
reverse(head);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/reverse-word-linked-list-node/
1273
Chapter 220
Input : 1->2->3->4->5->6->7->8->9->10->NULL
k = 3
Output :3->2->1->4->5->6->7->8->9->10->NULL
Input :10->18->20->25->35->NULL
k = 2
Output :18->10->20->25->35->NULL
1274
Chapter 220. Reverse first K elements of given linked list
1275
Chapter 220. Reverse first K elements of given linked list
1276
Chapter 220. Reverse first K elements of given linked list
reverseKNodes(&head, k);
return 0;
}
1277
Chapter 220. Reverse first K elements of given linked list
Output:
Given list
1 2 3 4 5
Modified list
3 2 1 4 5
Source
https://www.geeksforgeeks.org/reverse-first-k-elements-given-linked-list/
1278
Chapter 221
Reverse nodes of a linked list without affecting the special characters - GeeksforGeeks
Given a linked list of alphabets and special characters. Reverse the given linked list without
affecting the position of the special characters.
Examples:
Input: g -> @ -> e -> # -> e -> $ -> k -> s -> NULL
Output: s -> @ -> k -> # -> e -> $ -> e -> g -> NULL
Explanation: Here we can see that in the output the position of special char-
acter in not change and also linked list is reverse.
The idea is to traverse the linked list and store the characters excluding the special characters
in a temporary array. Again traverse the linked list and copy elements from the array to
the nodes of the linked list in a reverse manner.
Below is the step by step algorithm:
• if the current element is an alphabet, store that element of the linked list to
TEMP_ARR.
• else, increase node pointer by one
1279
Chapter 221. Reverse nodes of a linked list without affecting the special characters
C++
#include <iostream>
char TEMP_ARR[size];
int i = 0;
current = *head_ref;
// Traverse the linked list again
1280
Chapter 221. Reverse nodes of a linked list without affecting the special characters
1281
Chapter 221. Reverse nodes of a linked list without affecting the special characters
push(&head, 's');
push(&head, '$');
push(&head, 'k');
push(&head, 'e');
push(&head, 'e');
push(&head, '@');
push(&head, '#');
push(&head, 'g');
push(&head, 'r');
push(&head, 'o');
push(&head, 'f');
push(&head, 's');
push(&head, '$');
push(&head, 'k');
push(&head, 'e');
push(&head, 'e');
push(&head, 'g');
reverse(&head, 13);
return 0;
}
Java
1282
Chapter 221. Reverse nodes of a linked list without affecting the special characters
int size)
{
Node current = head_ref;
int i = 0;
current = head_ref;
1283
Chapter 221. Reverse nodes of a linked list without affecting the special characters
return head_ref;
}
// Driver Code
public static void main(String rags[])
{
/* Start with the empty list */
Node head = null;
1284
Chapter 221. Reverse nodes of a linked list without affecting the special characters
reverse(head, 13);
Output:
Improved By : andrew1234
Source
https://www.geeksforgeeks.org/reverse-nodes-of-a-linked-list-without-affecting-the-special-characters/
1285
Chapter 222
N=2
Rotated List:
Examples:
Input : a b c d e N = 2
Output : c d e a b
Input : a b c d e f g h N = 4
Output : e f g h a b c d
Asked in Amazon
1286
Chapter 222. Rotate Doubly linked list by N nodes
To rotate the Doubly linked list, we need to change next of Nth node to NULL, next of last
node to previous head node, and prev of head node to last node and finally change head to
(N+1)th node and prev of new head node to NULL (Prev of Head node in doubly linked
list is NULL)
So we need to get hold of three nodes: Nth node, (N+1)th node and last node. Traverse the
list from beginning and stop at Nth node. Store pointer to Nth node. We can get (N+1)th
node using NthNode->next. Keep traversing till end and store pointer to last node also.
Finally, change pointers as stated above and at Last Print Rotated List using
PrintList Function.
1287
Chapter 222. Rotate Doubly linked list by N nodes
1288
Chapter 222. Rotate Doubly linked list by N nodes
new_node->next = (*head_ref);
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
*head_ref = new_node;
}
// Driver's Code
int main(void)
{
/* Start with the empty list */
struct Node* head = NULL;
int N = 2;
return 0;
}
Output:
1289
Chapter 222. Rotate Doubly linked list by N nodes
a b c d e
Rotated Linked list
c d e a b
Source
https://www.geeksforgeeks.org/rotate-doubly-linked-list-n-nodes/
1290
Chapter 223
Input: 1->2->3->4->5->6->7->8->9->NULL,
k = 3
d = 1
Output: 3->1->2->6->4->5->9->7->8->NULL
Explanation: Here blocks of size 3 are
rotated towards right(as d is positive)
by 1.
Input: 1->2->3->4->5->6->7->8->9->10->
11->12->13->14->15->NULL,
k = 4
d = -1
Output: 2->3->4->1->6->7->8->5->10->11
->12->9->14->15->13->NULL
Explanation: Here, at the end of linked
list, remaining nodes are less than k, i.e.
only three nodes are left while k is 4.
Rotate those 3 nodes also by d.
1291
Chapter 223. Rotate Linked List block wise
// Rotate Clockwise
if (d > 0) {
struct Node* temp = blockHead;
for (int i = 1; temp->next->next &&
i < k - 1; i++)
temp = temp->next;
blockTail->next = blockHead;
*tail = temp;
return rotateHelper(blockTail, temp,
d - 1, tail, k);
}
// Rotate anti-Clockwise
if (d < 0) {
blockTail->next = blockHead;
*tail = blockHead;
return rotateHelper(blockHead->next,
blockHead, d + 1, tail, k);
}
}
1292
Chapter 223. Rotate Linked List block wise
/* UTILITY FUNCTIONS */
/* Function to push a node */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node = new Node;
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
1293
Chapter 223. Rotate Linked List block wise
}
}
return (0);
}
Output:
Improved By : codeShaurya
Source
https://www.geeksforgeeks.org/rotate-linked-list-block-wise/
1294
Chapter 224
#include<stdio.h>
#include<stdlib.h>
1295
Chapter 224. Rotate a Linked List
{
if (k == 0)
return;
/* UTILITY FUNCTIONS */
/* Function to push a node */
void push (struct Node** head_ref, int new_data)
{
1296
Chapter 224. Rotate a Linked List
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
return (0);
}
Java
1297
Chapter 224. Rotate a Linked List
class LinkedList
{
Node head; // head of list
1298
Chapter 224. Rotate a Linked List
current.next = head;
void printList()
{
Node temp = head;
while(temp != null)
{
System.out.print(temp.data+" ");
temp = temp.next;
}
System.out.println();
}
1299
Chapter 224. Rotate a Linked List
System.out.println("Given list");
llist.printList();
llist.rotate(4);
Python
# Node class
class Node:
class LinkedList:
1300
Chapter 224. Rotate a Linked List
print temp.data,
temp = temp.next
1301
Chapter 224. Rotate a Linked List
kthNode.next = None
Output:
Time Complexity: O(n) where n is the number of nodes in Linked List. The code traverses
the linked list only once.
Source
https://www.geeksforgeeks.org/rotate-a-linked-list/
1302
Chapter 225
For example, if the key to be searched is 15 and linked list is 14->21->11->30->10, then
function should return false. If key to be searched is 14, then the function should return
true.
Iterative Solution
1303
Chapter 225. Search an element in a Linked List (Iterative and Recursive)
1304
Chapter 225. Search an element in a Linked List (Iterative and Recursive)
14->21->11->30->10 */
push(&head, 10);
push(&head, 30);
push(&head, 11);
push(&head, 21);
push(&head, 14);
Java
//Node class
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
1305
Chapter 225. Search an element in a Linked List (Iterative and Recursive)
{
Node current = head; //Initialize current
while (current != null)
{
if (current.data == x)
return true; //data found
current = current.next;
}
return false; //data not found
}
if (llist.search(llist.head, 21))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Pratik Agarwal
Python
# Node class
class Node:
1306
Chapter 225. Search an element in a Linked List (Iterative and Recursive)
class LinkedList:
def __init__(self):
self.head = None # Initialize head as None
current = current.next
1307
Chapter 225. Search an element in a Linked List (Iterative and Recursive)
if llist.search(21):
print("Yes")
else:
print("No")
Output:
Yes
Recursive Solution
bool search(head, x)
1) If head is NULL, return false.
2) If head's key is same as x, return true;
2) Else return search(head->next, x)
1308
Chapter 225. Search an element in a Linked List (Iterative and Recursive)
Java
// Node class
1309
Chapter 225. Search an element in a Linked List (Iterative and Recursive)
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
1310
Chapter 225. Search an element in a Linked List (Iterative and Recursive)
{
// Start with the empty list
LinkedList llist = new LinkedList();
if (llist.search(llist.head, 21))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Pratik Agarwal
Output:
Yes
Python
# Node class
class Node:
# Function to initialise
# the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
class LinkedList:
def __init__(self):
self.head = None # Initialize head as None
1311
Chapter 225. Search an element in a Linked List (Iterative and Recursive)
# Base case
if(not li):
return False
# If key is present in
# current node, return true
if(li.data == key):
return True
# Driver Code
if __name__=='__main__':
li = LinkedList()
li.push(1)
li.push(2)
li.push(3)
li.push(4)
key = 4
if li.search(li.head,key):
print("Yes")
else:
print("No")
Output:
1312
Chapter 225. Search an element in a Linked List (Iterative and Recursive)
Yes
This article is contributed by Ravi. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Improved By : CodeDaemon
Source
https://www.geeksforgeeks.org/search-an-element-in-a-linked-list-iterative-and-recursive/
1313
Chapter 226
Input: 17->15->8->12->10->5->4->1->7->6->NULL
Output: 8->12->10->4->6->17->15->5->1->7->NULL
Input: 8->12->10->5->4->1->6->NULL
Output: 8->12->10->4->6->5->1->NULL
Method 1
The idea is to get pointer to the last node of list. And then traverse the list starting from
the head node and move the odd valued nodes from their current position to end of the list.
Thanks to blunderboy for suggesting this method.
Algorithm:
…1) Get pointer to the last node.
1314
Chapter 226. Segregate even and odd nodes in a Linked List
// 10->8->17->17->15
/* Do following steps only if there is any even node */
if (curr->data%2 == 0)
{
/* Change the head pointer to point to first even node */
*head_ref = curr;
1315
Chapter 226. Segregate even and odd nodes in a Linked List
/* If there are more than 1 odd nodes and end of original list is
odd then move this node to end to maintain same order of odd
numbers in modified list */
if (new_end!=end && (end->data)%2 != 0)
{
prev->next = end->next;
end->next = NULL;
new_end->next = end;
}
return;
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginning */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
1316
Chapter 226. Segregate even and odd nodes in a Linked List
push(&head, 11);
push(&head, 10);
push(&head, 8);
push(&head, 6);
push(&head, 4);
push(&head, 2);
push(&head, 0);
segregateEvenOdd(&head);
1317
Chapter 226. Segregate even and odd nodes in a Linked List
return 0;
}
Java
void segregateEvenOdd()
{
Node end = head;
Node prev = null;
Node curr = head;
1318
Chapter 226. Segregate even and odd nodes in a Linked List
1319
Chapter 226. Segregate even and odd nodes in a Linked List
llist.segregateEvenOdd();
Output:
1320
Chapter 226. Segregate even and odd nodes in a Linked List
while(currNode != NULL){
int val = currNode -> data;
1321
Chapter 226. Segregate even and odd nodes in a Linked List
if(val % 2 == 0) {
if(evenStart == NULL){
evenStart = currNode;
evenEnd = evenStart;
}
else{
evenEnd -> next = currNode;
evenEnd = evenEnd -> next;
}
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginning */
1322
Chapter 226. Segregate even and odd nodes in a Linked List
push(&head, 11);
push(&head, 10);
push(&head, 9);
push(&head, 6);
push(&head, 4);
push(&head, 1);
push(&head, 0);
segregateEvenOdd(&head);
1323
Chapter 226. Segregate even and odd nodes in a Linked List
return 0;
}
Java
class LinkedList {
while(currentNode != null) {
int element = currentNode.data;
if(element % 2 == 0) {
if(evenStart == null) {
evenStart = currentNode;
evenEnd = evenStart;
} else {
evenEnd.next = currentNode;
1324
Chapter 226. Segregate even and odd nodes in a Linked List
evenEnd = evenEnd.next;
}
} else {
if(oddStart == null) {
oddStart = currentNode;
oddEnd = oddStart;
} else {
oddEnd.next = currentNode;
oddEnd = oddEnd.next;
}
}
// Move head pointer one step in forward direction
currentNode = currentNode.next;
}
evenEnd.next = oddStart;
oddEnd.next = null;
head=evenStart;
}
1325
Chapter 226. Segregate even and odd nodes in a Linked List
{
System.out.print(temp.data+" ");
temp = temp.next;
}
System.out.println();
}
llist.segregateEvenOdd();
Output:
Source
https://www.geeksforgeeks.org/segregate-even-and-odd-elements-in-a-linked-list/
1326
Chapter 227
Segregate even and odd nodes in a Linked List using Deque - GeeksforGeeks
Given a Linked List of integers. The task is to write a program to modify the linked list
such that all even numbers appear before all the odd numbers in the modified linked list. It
is not needed to keep the order of even and odd nodes same as that of the original list, the
task is just to rearrange the nodes such that all even valued nodes appear before the odd
valued nodes.
See Also: Segregate even and odd nodes in a Linked List
Examples:
Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> NULL
Output: 10 -> 8 -> 6 -> 4 -> 2 -> 1 -> 3 -> 5 -> 7 -> 9 -> NULL
Input: 4 -> 3 -> 2 -> 1 -> NULL
Output: 2 -> 4 -> 3 -> 1 -> NULL
The idea is to iteratively push all the elements of the linked list to deque as per the below
conditions:
• Start traversing the linked list and if an element is even then push it to the front of
the Deque and,
• If the element is odd then push it to the back of the Deque.
Finally, replace all elements of the linked list with the elements of Deque starting from the
first element.
Below is the implementation of the above approach:
1327
Chapter 227. Segregate even and odd nodes in a Linked List using Deque
/*UTILITY FUNCTIONS*/
/* Push a node to linked list. Note that this function
changes the head */
void push(struct Node** head_ref, char new_data)
{
/* allocate node */
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
// Declaring a Deque
deque<int> d;
1328
Chapter 227. Segregate even and odd nodes in a Linked List using Deque
temp = head;
// Driver code
int main()
{
struct Node* head = NULL;
push(&head, 10);
push(&head, 9);
push(&head, 8);
push(&head, 7);
push(&head, 6);
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
evenOdd(head);
1329
Chapter 227. Segregate even and odd nodes in a Linked List using Deque
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/segregate-even-and-odd-nodes-in-a-linked-list-using-deque/
1330
Chapter 228
1331
Chapter 228. Select a Random Node from a Singly Linked List
result = head->key
(2) Initialize n = 2
(3) Now one by one consider all nodes from 2nd node onward.
(3.a) Generate a random number from 0 to n-1.
Let the generated random number is j.
(3.b) If j is equal to 0 (we could choose other fixed number
between 0 to n-1), then replace result with current node.
(3.c) n = n+1
(3.d) current = current->next
1332
Chapter 228. Select a Random Node from a Singly Linked List
return new_node;
}
1333
Chapter 228. Select a Random Node from a Singly Linked List
{
struct Node *head = NULL;
push(&head, 5);
push(&head, 20);
push(&head, 4);
push(&head, 3);
push(&head, 30);
printRandom(head);
return 0;
}
Java
import java.util.*;
/* Node Class */
static class Node {
int data;
Node next;
// If list is empty
if (node == null) {
return;
}
1334
Chapter 228. Select a Random Node from a Singly Linked List
Math.abs(UUID.randomUUID().getMostSignificantBits());
list.printrandom(head);
}
}
Python
import random
# Node class
class Node:
1335
Chapter 228. Select a Random Node from a Singly Linked List
class LinkedList:
# If list is empty
if self.head is None:
return
1336
Chapter 228. Select a Random Node from a Singly Linked List
Note that the above program is based on outcome of a random function and may produce
different output.
How does this work?
Let there be total N nodes in list. It is easier to understand from last node.
The probability that last node is result simply 1/N [For last or N’th node, we generate a
random number between 0 to N-1 and make last node as result if the generated number is
0 (or any other fixed number]
The probability that second last node is result should also be 1/N.
Similarly we can show probability for 3rd last node and other nodes.
This article is contributed by Rajeev. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/select-a-random-node-from-a-singly-linked-list/
1337
Chapter 229
1338
Chapter 229. Self Organizing List : Count Method
Examples:
Input : list : 1, 2, 3, 4, 5
searched : 4
Output : list : 4, 1, 2, 3, 5
Input : list : 4, 1, 2, 3, 5
searched : 5
searched : 5
searched : 2
Output : list : 5, 2, 4, 1, 3
Explanation : 5 is searched 2 times (i.e. the
most searched) 2 is searched 1 time and 4 is
also searched 1 time (but since 2 is searched
recently, it is kept ahead of 4) rest are not
searched, so they maintained order in which
they were inserted.
1339
Chapter 229. Self Organizing List : Count Method
1340
Chapter 229. Self Organizing List : Count Method
// if key is found
if (current->value == key) {
// if it is to be placed at beginning
if (temp == head)
head = current;
else
temp_prev->next = current;
}
}
return true;
}
prev = current;
current = current->next;
}
return false;
}
1341
Chapter 229. Self Organizing List : Count Method
// Driver Code
int main()
{
/* inserting five values */
insert_self_list(1);
insert_self_list(2);
insert_self_list(3);
insert_self_list(4);
insert_self_list(5);
search_self_list(4);
search_self_list(2);
display();
search_self_list(4);
search_self_list(4);
search_self_list(5);
display();
search_self_list(5);
search_self_list(2);
search_self_list(2);
search_self_list(2);
display();
return 0;
}
Output:
1342
Chapter 229. Self Organizing List : Count Method
List: 1(0) --> 2(0) --> 3(0) --> 4(0) --> 5(0)
List: 2(1) --> 4(1) --> 1(0) --> 3(0) --> 5(0)
List: 4(3) --> 5(1) --> 2(1) --> 1(0) --> 3(0)
List: 2(4) --> 4(3) --> 5(2) --> 1(0) --> 3(0)
Source
https://www.geeksforgeeks.org/self-organizing-list-count-method/
1343
Chapter 230
1344
Chapter 230. Self Organizing List : Move to Front Method
Examples:
Input : list : 1, 2, 3, 4, 5, 6
searched: 4
Output : list : 4, 1, 2, 3, 5, 6
Input : list : 4, 1, 2, 3, 5, 6
searched : 2
Output : list : 2, 4, 1, 3, 5, 6
1345
Chapter 230. Self Organizing List : Move to Front Method
struct self_list {
int value;
struct self_list* next;
};
// if key found
if (current->value == key) {
1346
Chapter 230. Self Organizing List : Move to Front Method
// Driver Code
int main()
{
/* inserting five values */
insert_self_list(1);
insert_self_list(2);
insert_self_list(3);
insert_self_list(4);
insert_self_list(5);
1347
Chapter 230. Self Organizing List : Move to Front Method
return 0;
}
Output:
Searched: 4
List: 4 --> 1 --> 2 --> 3 --> 5
Searched: 2
List: 2 --> 4 --> 1 --> 3 --> 5
Source
https://www.geeksforgeeks.org/self-organizing-list-move-front-method/
1348
Chapter 231
randomLevel()
lvl := 1
//random() that returns a random value in [0...1)
while random() < p and lvl < MaxLevel do
lvl := lvl + 1
return lvl
MaxLevel is the upper bound on number of levels in the skip list. It can be determined as
1349
Chapter 231. Skip List | Set 2 (Insertion)
1. Key of next node is less than key to be inserted then we keep on moving forward on
the same level
2. Key of next node is greater than the key to be inserted then we store the pointer to
current node i at update[i] and move one level down and continue our search.
At the level 0, we will definitely find a position to insert given key. Following is the psuedo
code for the insertion algorithm –
Insert(list, searchKey)
local update[0...MaxLevel+1]
x := list -> header
for i := list -> level downto 0 do
while x -> forward[i] -> key forward[i]
update[i] := x
x := x -> forward[0]
lvl := randomLevel()
if lvl > list -> level then
for i := list -> level + 1 to lvl do
update[i] := list -> header
list -> level := lvl
x := makeNode(lvl, searchKey, value)
for i := 0 to level do
x -> forward[i] := update[i] -> forward[i]
update[i] -> forward[i] := x
Here update[i] holds the pointer to node at level i from which we moved down to level i-1
and pointer of node left to insertion position at level 0. Consider this example where we
want to insert key 17 –
1350
Chapter 231. Skip List | Set 2 (Insertion)
#include <bits/stdc++.h>
using namespace std;
1351
Chapter 231. Skip List | Set 2 (Insertion)
};
1352
Chapter 231. Skip List | Set 2 (Insertion)
{
float r = (float)rand()/RAND_MAX;
int lvl = 0;
while (r < P && lvl < MAXLVL)
{
lvl++;
r = (float)rand()/RAND_MAX;
}
return lvl;
};
1353
Chapter 231. Skip List | Set 2 (Insertion)
1354
Chapter 231. Skip List | Set 2 (Insertion)
}
};
lst.insertElement(3);
lst.insertElement(6);
lst.insertElement(7);
lst.insertElement(9);
lst.insertElement(12);
lst.insertElement(19);
lst.insertElement(17);
lst.insertElement(26);
lst.insertElement(21);
lst.insertElement(25);
lst.displayList();
}
Python
import random
class Node(object):
'''
Class to implement node
'''
def __init__(self, key, level):
self.key = key
class SkipList(object):
'''
Class for Skip list
'''
def __init__(self, max_lvl, P):
# Maximum level for this skip list
self.MAXLVL = max_lvl
1355
Chapter 231. Skip List | Set 2 (Insertion)
'''
start from highest level of skip list
move the current reference forward while key
is greater than key of node next to current
Otherwise inserted current in update and
move one level down and continue search
'''
for i in range(self.level, -1, -1):
while current.forward[i] and \
current.forward[i].key < key:
current = current.forward[i]
update[i] = current
'''
reached level 0 and forward reference to
right, which is desired position to
insert key.
'''
current = current.forward[0]
1356
Chapter 231. Skip List | Set 2 (Insertion)
'''
if current is NULL that means we have reached
to end of the level or current's key is not equal
to key to insert that means we have to insert
node between update[0] and current node
'''
if current == None or current.key != key:
# Generate a random level for node
rlevel = self.randomLevel()
'''
If random level is greater than list's current
level (node with highest level inserted in
list so far), initialize update value with reference
to header for further use
'''
if rlevel > self.level:
for i in range(self.level+1, rlevel+1):
update[i] = self.header
self.level = rlevel
1357
Chapter 231. Skip List | Set 2 (Insertion)
lst.insertElement(6)
lst.insertElement(7)
lst.insertElement(9)
lst.insertElement(12)
lst.insertElement(19)
lst.insertElement(17)
lst.insertElement(26)
lst.insertElement(21)
lst.insertElement(25)
lst.displayList()
main()
Output:
*****Skip List*****
Level 0: 3 6 7 9 12 17 19 21 25 26
Level 1: 3 6 12 17 25
Level 2: 6 12 17 25
Level 3: 12 17 25
• ftp://ftp.cs.umd.edu/pub/skipLists/skiplists.pdf
Source
https://www.geeksforgeeks.org/skip-list-set-2-insertion/
1358
Chapter 232
1. Key of next node is less than search key then we keep on moving forward on the same
level.
2. Key of next node is greater than the key to be inserted then we store the pointer to
current node i at update[i] and move one level down and continue our search.
At the lowest level (0), if the element next to the rightmost element (update[0]) has key
equal to the search key, then we have found key otherwise failure.
Following is the pseudo code for searching element –
Search(list, searchKey)
x := list -> header
-- loop invariant: x -> key level downto 0 do
while x -> forward[i] -> key forward[i]
x := x -> forward[0]
if x -> key = searchKey then return x -> value
else return failure
1359
Chapter 232. Skip List | Set 3 (Searching and Deletion)
Delete(list, searchKey)
local update[0..MaxLevel+1]
x := list -> header
for i := list -> level downto 0 do
while x -> forward[i] -> key forward[i]
update[i] := x
x := x -> forward[0]
if x -> key = searchKey then
for i := 0 to list -> level do
if update[i] -> forward[i] � x then break
update[i] -> forward[i] := x -> forward[i]
free(x)
while list -> level > 0 and list -> header -> forward[list -> level] = NIL do
list -> level := list -> level – 1
1360
Chapter 232. Skip List | Set 3 (Searching and Deletion)
Here at level 3, there is no element (arrow in red) after deleting element 6. So we will
decrement level of skip list by 1.
Following is the code for searching and deleting element from Skip List –
C++
#include <bits/stdc++.h>
using namespace std;
1361
Chapter 232. Skip List | Set 3 (Searching and Deletion)
this->key = key;
1362
Chapter 232. Skip List | Set 3 (Searching and Deletion)
int lvl = 0;
while(r < P && lvl < MAXLVL)
{
lvl++;
r = (float)rand()/RAND_MAX;
}
return lvl;
};
1363
Chapter 232. Skip List | Set 3 (Searching and Deletion)
1364
Chapter 232. Skip List | Set 3 (Searching and Deletion)
{
while(current->forward[i] != NULL &&
current->forward[i]->key < key)
current = current->forward[i];
update[i] = current;
}
update[i]->forward[i] = current->forward[i];
}
1365
Chapter 232. Skip List | Set 3 (Searching and Deletion)
{
while(current->forward[i] &&
current->forward[i]->key < key)
current = current->forward[i];
lst.insertElement(3);
lst.insertElement(6);
lst.insertElement(7);
lst.insertElement(9);
lst.insertElement(12);
1366
Chapter 232. Skip List | Set 3 (Searching and Deletion)
lst.insertElement(19);
lst.insertElement(17);
lst.insertElement(26);
lst.insertElement(21);
lst.insertElement(25);
lst.displayList();
//Delete node 19
lst.deleteElement(19);
lst.displayList();
}
Python
import random
class Node(object):
'''
Class to implement node
'''
def __init__(self, key, level):
self.key = key
class SkipList(object):
'''
Class for Skip list
'''
def __init__(self, max_lvl, P):
# Maximum level for this skip list
self.MAXLVL = max_lvl
1367
Chapter 232. Skip List | Set 3 (Searching and Deletion)
'''
start from highest level of skip list
move the current reference forward while key
is greater than key of node next to current
Otherwise inserted current in update and
move one level down and continue search
'''
for i in range(self.level, -1, -1):
while current.forward[i] and \
current.forward[i].key < key:
current = current.forward[i]
update[i] = current
'''
reached level 0 and forward reference to
right, which is desired position to
insert key.
'''
current = current.forward[0]
'''
if current is NULL that means we have reached
to end of the level or current's key is not equal
to key to insert that means we have to insert
node between update[0] and current node
'''
if current == None or current.key != key:
# Generate a random level for node
rlevel = self.randomLevel()
1368
Chapter 232. Skip List | Set 3 (Searching and Deletion)
'''
If random level is greater than list's current
level (node with highest level inserted in
list so far), initialize update value with reference
to header for further use
'''
if rlevel > self.level:
for i in range(self.level+1, rlevel+1):
update[i] = self.header
self.level = rlevel
'''
start from highest level of skip list
move the current reference forward while key
is greater than key of node next to current
Otherwise inserted current in update and
move one level down and continue search
'''
for i in range(self.level, -1, -1):
while(current.forward[i] and \
current.forward[i].key < search_key):
current = current.forward[i]
update[i] = current
'''
reached level 0 and advance reference to
right, which is prssibly our desired node
'''
current = current.forward[0]
1369
Chapter 232. Skip List | Set 3 (Searching and Deletion)
'''
start from lowest level and rearrange references
just like we do in singly linked list
to remove target node
'''
for i in range(self.level+1):
'''
If at level i, next node is not target
node, break the loop, no need to move
further level
'''
if update[i].forward[i] != current:
break
update[i].forward[i] = current.forward[i]
'''
start from highest level of skip list
move the current reference forward while key
is greater than key of node next to current
Otherwise inserted current in update and
move one level down and continue search
'''
for i in range(self.level, -1, -1):
while(current.forward[i] and\
current.forward[i].key < key):
current = current.forward[i]
1370
Chapter 232. Skip List | Set 3 (Searching and Deletion)
# Delete node 19
lst.deleteElement(19)
lst.displayList()
main()
Output:
1371
Chapter 232. Skip List | Set 3 (Searching and Deletion)
*****Skip List*****
Level 0: 3 6 7 9 12 17 19 21 25 26
Level 1: 3 17 19 21 26
Level 2: 17 19 21
Found key: 19
Successfully deleted key 19
*****Skip List*****
Level 0: 3 6 7 9 12 17 21 25 26
Level 1: 3 17 21 26
Level 2: 17 21
Source
https://www.geeksforgeeks.org/skip-list-set-3-searching-deletion/
1372
Chapter 233
Naive Approach: Sort the given doubly linked list using insertion sort technique.
Time Complexity: O(nk)
Auxiliary Space: O(1)
Efficient Approach: We can sort the list using the MIN HEAP data structure. The
approach has been explained in Sort a nearly sorted (or K sorted) array. We only have to
be careful while traversing the input doubly linked list and adjusting the required next and
previous links in the final sorted list.
1373
Chapter 233. Sort a k sorted doubly linked list
1374
Chapter 233. Sort a k sorted doubly linked list
else {
last->next = pq.top();
pq.top()->prev = last;
last = pq.top();
}
1375
Chapter 233. Sort a k sorted doubly linked list
int k = 2;
return 0;
}
1376
Chapter 233. Sort a k sorted doubly linked list
Output:
Source
https://www.geeksforgeeks.org/sort-k-sorted-doubly-linked-list/
1377
Chapter 234
1378
Chapter 234. Sort a linked list of 0s, 1s and 2s
int i = 0;
ptr = head;
1379
Chapter 234. Sort a linked list of 0s, 1s and 2s
sortList(head);
return 0;
}
Java
1380
Chapter 234. Sort a linked list of 0s, 1s and 2s
void sortList()
{
// initialise count of 0 1 and 2 as 0
int count[] = {0, 0, 0};
int i = 0;
ptr = head;
/* Utility functions */
1381
Chapter 234. Sort a linked list of 0s, 1s and 2s
llist.sortList();
Python
1382
Chapter 234. Sort a linked list of 0s, 1s and 2s
# head of list
self.head = None
def sortList(self):
ptr = self.head
i = 0
ptr = self.head
# Utility functions
# Inserts a new Node at front of the list.
def push(self, new_data):
1383
Chapter 234. Sort a linked list of 0s, 1s and 2s
llist.sortList()
Output:
1384
Chapter 234. Sort a linked list of 0s, 1s and 2s
Source
https://www.geeksforgeeks.org/sort-a-linked-list-of-0s-1s-or-2s/
1385
Chapter 235
Input : 2->1->2->1->1->2->0->1->0
Output : 0->0->1->1->1->1->2->2->2
Input : 2->1->0
Output : 0->1->2
We have discussed a solution in below post that works by changing data of nodes.
Sort a linked list of 0s, 1s and 2s
The above solution does not work when these values have associated data with them. For
example, these three represent three colors and different types of objects associated with
the colors and we want to sort objects (connected with a linked list) based on colors.
In this post, a new solution is discussed that works by changing links.
Iterate through the linked list. Maintain 3 pointers named zero, one and two to point to
current ending nodes of linked lists containing 0, 1, and 2 respectively. For every traversed
node, we attach it to the end of its corresponding list. Finally we link all three lists. To
avoid many null checks, we use three dummy pointers zeroD, oneD and twoD that work as
dummy headers of three lists.
1386
Chapter 235. Sort a linked list of 0s, 1s and 2s by changing links
// Traverse list
Node* curr = head;
while (curr) {
if (curr->data == 0) {
zero->next = curr;
zero = zero->next;
curr = curr->next;
} else if (curr->data == 1) {
one->next = curr;
one = one->next;
curr = curr->next;
} else {
two->next = curr;
two = two->next;
curr = curr->next;
}
}
1387
Chapter 235. Sort a linked list of 0s, 1s and 2s by changing links
one->next = twoD->next;
two->next = NULL;
// Updated head
head = zeroD->next;
return head;
}
head = sortList(head);
1388
Chapter 235. Sort a linked list of 0s, 1s and 2s by changing links
return 0;
}
Output :
Source
https://www.geeksforgeeks.org/sort-linked-list-0s-1s-2s-changing-links/
1389
Chapter 236
Sort a linked list that is sorted alternating ascending and descending orders? - Geeks-
forGeeks
Given a Linked List. The Linked List is in alternating ascending and descending orders.
Sort the list efficiently.
Example:
A Simple Solution is to use Merge Sort for linked List. This solution takes O(n Log n)
time.
An Efficient Solution works in O(n) time. Below are all steps.
1. Separate two lists.
2. Reverse the one with descending order
3. Merge both lists.
Below are C++ and Java implementations of above algorithm.
C++
1390
Chapter 236. Sort a linked list that is sorted alternating ascending and descending orders?
1391
Chapter 236. Sort a linked list that is sorted alternating ascending and descending orders?
1392
Chapter 236. Sort a linked list that is sorted alternating ascending and descending orders?
ascn->next = NULL;
dscn->next = NULL;
*Ahead = (*Ahead)->next;
*Dhead = (*Dhead)->next;
}
sort(&head);
return 0;
}
Java
1393
Chapter 236. Sort a linked list that is sorted alternating ascending and descending orders?
Ahead = Ahead.next;
Dhead = Dhead.next;
1394
Chapter 236. Sort a linked list that is sorted alternating ascending and descending orders?
next = current.next;
current.next = prev;
prev = current;
current = next;
}
Dhead = prev;
return Dhead;
}
1395
Chapter 236. Sort a linked list that is sorted alternating ascending and descending orders?
if (curr != null)
{
dscn.next = curr;
dscn = dscn.next;
curr = curr.next;
}
}
ascn.next = null;
dscn.next = null;
}
llist.sort();
1396
Chapter 236. Sort a linked list that is sorted alternating ascending and descending orders?
Python
1397
Chapter 236. Sort a linked list that is sorted alternating ascending and descending orders?
def printList(self):
temp = self.head
while temp != None:
print temp.data,
temp = temp.next
print ''
# Driver program
llist = LinkedList()
1398
Chapter 236. Sort a linked list that is sorted alternating ascending and descending orders?
llist.head = llist.newNode(10)
llist.head.next = llist.newNode(40)
llist.head.next.next = llist.newNode(53)
llist.head.next.next.next = llist.newNode(30)
llist.head.next.next.next.next = llist.newNode(67)
llist.head.next.next.next.next.next = llist.newNode(12)
llist.head.next.next.next.next.next.next = llist.newNode(89)
llist.sort()
Output:
Source
https://www.geeksforgeeks.org/how-to-sort-a-linked-list-that-is-sorted-alternating-ascending-and-descending-order
1399
Chapter 237
Input : 5 -> 10
output: 5 -> 10
1400
Chapter 237. Sort linked list which is already sorted on absolute values
C++
1401
Chapter 237. Sort linked list which is already sorted on absolute values
// Traverse list
while (curr != NULL)
{
// If curr is smaller than prev, then
// it must be moved to head
if (curr->data < prev->data)
{
// Detach curr from linked list
prev->next = curr->next;
// Update current
curr = prev;
}
// Move current
curr = curr->next;
}
}
// Driver code
int main()
{
Node* head = NULL;
push(&head, -5);
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, -2);
push(&head, 1);
push(&head, 0);
sortList(&head);
1402
Chapter 237. Sort linked list which is already sorted on absolute values
return 0;
}
Java
// Traverse list
while(curr != null)
{
// If curr is smaller than prev, then
// it must be moved to head
if(curr.data < prev.data)
{
// Detach curr from linked list
prev.next = curr.next;
// Update current
curr = prev;
}
1403
Chapter 237. Sort linked list which is already sorted on absolute values
else
prev = curr;
// Move current
curr = curr.next;
}
return head;
}
1404
Chapter 237. Sort linked list which is already sorted on absolute values
llist.push(0);
llist.head = llist.sortedList(head);
Output:
Original list :
0 -> 1 -> -2 -> 3 -> 4 -> 5 -> -5
Sorted list :
-5 -> -2 -> 0 -> 1 -> 3 -> 4 -> 5
This article is contributed by Rahul Titare. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/sort-linked-list-already-sorted-absolute-values/
1405
Chapter 238
Approach: Find the first node in the list which is smaller than its previous node. Let it be
current. If no such node is present then list is already sorted. Else split the list into two
lists, first starting from head node till the current’s previous node and second starting
from current node till the end of the list. Reverse the second doubly linked list. Refer this
post. Now merge the first and second sorted doubly linked list. Refer merge procedure of
this post. The final merged list is the required sorted doubly linked list.
1406
Chapter 238. Sort the biotonic doubly linked list
1407
Chapter 238. Sort the biotonic doubly linked list
1408
Chapter 238. Sort the biotonic doubly linked list
new_node->data = new_data;
1409
Chapter 238. Sort the biotonic doubly linked list
printList(head);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/sort-biotonic-doubly-linked-list/
1410
Chapter 239
Input : 2 5 7 12 10 6 4 1
Output : 1 2 4 5 6 7 10 12
Input : 20 17 14 8 3
Output : 3 8 14 17 20
In the previous post, we split the bitonic doubly linked list, reverse the second half and
then merge both halves. In this post another alternative method is discussed. The idea is
to maintain two pointers, one pointing to head element initially and other pointing to last
element of doubly linked list. Compare both the elements and add the smaller element to
result list. Advance pointer of that element to next adjacent element. Repeat this until all
elements of input doubly linked list are added to result list.
Below is C++ implementation of above algorithm:
#include <bits/stdc++.h>
using namespace std;
1411
Chapter 239. Sort the biotonic doubly linked list | Set-2
1412
Chapter 239. Sort the biotonic doubly linked list | Set-2
1413
Chapter 239. Sort the biotonic doubly linked list | Set-2
1414
Chapter 239. Sort the biotonic doubly linked list | Set-2
head = sort(head);
return 0;
}
Output:
Original Doubly linked list:
2 5 7 12 10 6 4 1
Doubly linked list after sorting:
1 2 4 5 6 7 10 12
Source
https://www.geeksforgeeks.org/sort-the-biotonic-doubly-linked-list-set-2/
1415
Chapter 240
Sort the linked list in the order of elements appearing in the array - GeeksforGeeks
Given an array of size N and a Linked List where elements will be from the array but can
also be duplicated, sort the linked list in the order, elements are appearing in the array. It
may be assumed that the array covers all elements of the linked list.
arr[] =
list =
Sorted list =
Asked in Amazon
First, make a hash table that stores the frequencies of elements in linked list. Then, simply
traverse list and for each element of arr[i] check the frequency in the has table and modify
the data of list by arr[i] element upto its frequency and at last Print the list.
1416
Chapter 240. Sort the linked list in the order of elements appearing in the array
temp = head;
1417
Chapter 240. Sort the linked list in the order of elements appearing in the array
// equal to arr[i]
int frequency = hash[arr[i]];
while (frequency--) {
// Driver Code
int main()
{
struct Node* head = NULL;
int arr[] = { 5, 1, 3, 2, 8 };
int N = sizeof(arr) / sizeof(arr[0]);
Output :
Sort list:
5 -> 5 -> 1 -> 3 -> 2 -> 2 -> 8
1418
Chapter 240. Sort the linked list in the order of elements appearing in the array
Source
https://www.geeksforgeeks.org/sort-linked-list-order-elements-appearing-array/
1419
Chapter 241
1420
Chapter 241. Sorted Linked List to Balanced BST
Method 1 (Simple)
Following is a simple algorithm where we first find the middle node of list and make it root
of the tree to be constructed.
#include<stdio.h>
#include<stdlib.h>
1421
Chapter 241. Sorted Linked List to Balanced BST
/* This function counts the number of nodes in Linked List and then calls
sortedListToBSTRecur() to construct BST */
struct TNode* sortedListToBST(struct LNode *head)
{
/*Count the number of nodes in Linked List */
int n = countLNodes(head);
/* Construct BST */
return sortedListToBSTRecur(&head, n);
}
/* The main function that constructs balanced BST and returns root of it.
head_ref --> Pointer to pointer to head node of linked list
n --> No. of nodes in Linked List */
struct TNode* sortedListToBSTRecur(struct LNode **head_ref, int n)
{
/* Base Case */
if (n <= 0)
return NULL;
/* Allocate memory for root, and link the above constructed left
subtree with root */
struct TNode *root = newNode((*head_ref)->data);
root->left = left;
1422
Chapter 241. Sorted Linked List to Balanced BST
return root;
}
/* UTILITY FUNCTIONS */
1423
Chapter 241. Sorted Linked List to Balanced BST
return node;
}
return 0;
1424
Chapter 241. Sorted Linked List to Balanced BST
Java
class LinkedList {
LNode(int d)
{
data = d;
next = prev = null;
}
}
TNode(int d)
{
data = d;
left = right = null;
}
}
/* Construct BST */
return sortedListToBSTRecur(n);
}
1425
Chapter 241. Sorted Linked List to Balanced BST
return root;
}
/* UTILITY FUNCTIONS */
/* A utility function that returns count of nodes in a
given Linked List */
int countNodes(LNode head)
{
int count = 0;
LNode temp = head;
while (temp != null)
{
temp = temp.next;
count++;
}
return count;
}
1426
Chapter 241. Sorted Linked List to Balanced BST
/* allocate node */
LNode new_node = new LNode(new_data);
1427
Chapter 241. Sorted Linked List to Balanced BST
llist.push(3);
llist.push(2);
llist.push(1);
Output:
Source
https://www.geeksforgeeks.org/sorted-linked-list-to-balanced-bst/
1428
Chapter 242
Algorithm:
Allocate memory for the newly inserted node and put data in the newly allocated node. Let
the pointer to the new node be new_node. After memory allocation, following are the three
cases that need to be handled.
1429
Chapter 242. Sorted insert for circular linked list
#include<stdio.h>
#include<stdlib.h>
1430
Chapter 242. Sorted insert for circular linked list
new_node->next = *head_ref;
*head_ref = new_node;
}
new_node->next = current->next;
current->next = new_node;
}
}
if(start != NULL)
{
temp = start;
printf("\n");
do {
printf("%d ", temp->data);
temp = temp->next;
} while(temp != start);
}
}
1431
Chapter 242. Sorted insert for circular linked list
temp->data = arr[i];
sortedInsert(&start, temp);
}
printList(start);
return 0;
}
Java
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
class LinkedList
{
Node head;
// Constructor
LinkedList() { head = null; }
1432
Chapter 242. Sorted insert for circular linked list
current.next = new_node;
new_node.next = head;
head = new_node;
}
new_node.next = current.next;
current.next = new_node;
}
}
1433
Chapter 242. Sorted insert for circular linked list
list.printList();
}
}
Python
# Node class
class Node:
class LinkedList:
1434
Chapter 242. Sorted insert for circular linked list
current = self.head
new_node.next = current.next
current.next = new_node
list_size = len(arr)
1435
Chapter 242. Sorted insert for circular linked list
for i in range(list_size):
temp = Node(arr[i])
start.sortedInsert(temp)
start.printList()
Output:
1 2 11 12 56 90
Time Complexity: O(n) where n is the number of nodes in the given linked list.
Case 2 of the above algorithm/code can be optimized. To implement the suggested change
we need to modify the case 2 to following.
new_node->next = (*head_ref)->next;
(*head_ref)->next = new_node;
}
Source
https://www.geeksforgeeks.org/sorted-insert-for-circular-linked-list/
1436
Chapter 243
Sorted insert in a doubly linked list with head and tail pointers - GeeksforGeeks
A Doubly linked list is a linked list that consists of a set of sequentially linked records called
nodes. Each node contains two fields that are references to the previous and to the next
node in the sequence of nodes.
The task is to create a doubly linked list by inserting nodes such that list remains in ascending
order on printing from left to right. Also, we need to maintain two pointers, head (points
to first node) and tail (points to last node).
Examples:
Input : 40 50 10 45 90 100 95
Output :10 40 45 50 90 95 100
Input : 30 10 50 43 56 12
Output :10 12 30 43 50 56
Algorithm:
The task can be accomplished as:
1. If Linked list is empty then make both the left and right pointers point to the node
to be inserted and make its previous and next field point to NULL.
2. If node to be inserted has value less than the value of first node of linked list then
connect that node from previous field of first node.
3. If node to be inserted has value more than the value of last node of linked list then
connect that node from next field of last node.
4. If node to be inserted has value in between the value of first and last node, then check
for appropriate position and make connections.
1437
Chapter 243. Sorted insert in a doubly linked list with head and tail pointers
1438
Chapter 243. Sorted insert in a doubly linked list with head and tail pointers
1439
Chapter 243. Sorted insert in a doubly linked list with head and tail pointers
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/create-doubly-linked-list-using-double-pointer-inserting-nodes-list-remains-ascendin
1440
Chapter 244
List 2:
Final list:
1441
Chapter 244. Sorted merge of two sorted doubly circular linked lists
struct Node {
int data;
Node *next, *prev;
};
// if list is empty
1442
Chapter 244. Sorted merge of two sorted doubly circular linked lists
if (*head_ref == NULL) {
new_node->next = new_node;
new_node->prev = new_node;
}
else {
1443
Chapter 244. Sorted merge of two sorted doubly circular linked lists
}
}
return finalHead;
}
1444
Chapter 244. Sorted merge of two sorted doubly circular linked lists
// list 1:
insert(&head1, 8);
insert(&head1, 5);
insert(&head1, 3);
insert(&head1, 1);
// list 2:
insert(&head2, 11);
insert(&head2, 9);
insert(&head2, 7);
insert(&head2, 2);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/sorted-merge-of-two-sorted-doubly-circular-linked-lists/
1445
Chapter 245
1446
Chapter 245. Split a Circular Linked List into two halves
If there are odd number of nodes, then first list should contain one extra.
Thanks to Geek4u for suggesting the algorithm.
1) Store the mid and last pointers of the circular linked list using tortoise and hare algorithm.
2) Make the second half circular.
3) Make the first half circular.
4) Set head (or start) pointers of the two linked lists.
In the below implementation, if there are odd nodes in the given circular linked list then
the first result list has 1 more node than the second result list.
if(head == NULL)
return;
1447
Chapter 245. Split a Circular Linked List into two halves
fast_ptr = fast_ptr->next;
/* UTILITY FUNCTIONS */
/* Function to insert a node at the begining of a Circular
linked lsit */
void push(struct Node **head_ref, int data)
{
struct Node *ptr1 = (struct Node *)malloc(sizeof(struct Node));
struct Node *temp = *head_ref;
ptr1->data = data;
ptr1->next = *head_ref;
*head_ref = ptr1;
}
1448
Chapter 245. Split a Circular Linked List into two halves
getchar();
return 0;
}
Java
class LinkedList {
1449
Chapter 245. Split a Circular Linked List into two halves
int data;
Node next, prev;
Node(int d) {
data = d;
next = prev = null;
}
}
if (head == null) {
return;
}
1450
Chapter 245. Split a Circular Linked List into two halves
}
}
Python
# A node structure
class Node:
1451
Chapter 245. Split a Circular Linked List into two halves
self.next = None
ptr1.next = self.head
else:
ptr1.next = ptr1 # For the first node
self.head = ptr1
1452
Chapter 245. Split a Circular Linked List into two halves
if self.head is None:
return
head.push(12)
head.push(56)
head.push(2)
head.push(11)
1453
Chapter 245. Split a Circular Linked List into two halves
Output:
Source
https://www.geeksforgeeks.org/split-a-circular-linked-list-into-two-halves/
1454
Chapter 246
Squareroot(n)-th node in a
Linked List
Input : 1->2->3->4->5->NULL
Output : 2
Input : 10->20->30->40->NULL
Output : 20
Input : 10->20->30->40->50->60->70->80->90->NULL
Output : 30
Simple method: The simple method is to first find the total number of nodes present in
the linked list, then find the value of floor(squareroot(n)) where n is the total number of
nodes. Then traverse from the first node in the list to this position and return the node at
this position.
This method traverses the linked list 2 times.
Optimized approach: In this method, we can get the required node by traversing the
linked list once only. Below is the step by step algorithm for this approach.
1. Initialize two counters i and j both to 1 and a pointer sqrtn to NULL to traverse til
the required position is reached.
2. Start traversing the list using head node until the last node is reached.
1455
Chapter 246. Squareroot(n)-th node in a Linked List
3. While traversing check if the value of j is equal to sqrt(i). If the value is equal increment
both i and j and sqrtn to point sqrtn->next otherwise increment only i.
4. Now, when we will reach the last node of list i will contain value of n, j will contain
value of sqrt(i) and sqrtn will point to node at jth position.
#include<stdio.h>
#include<stdlib.h>
// increment j if j = sqrt(i)
j++;
}
i++;
head=head->next;
}
1456
Chapter 246. Squareroot(n)-th node in a Linked List
return 0;
}
Output:
1457
Chapter 246. Squareroot(n)-th node in a Linked List
Source
https://www.geeksforgeeks.org/squarerootnth-node-in-a-linked-list/
1458
Chapter 247
• Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow
condition.
• Pop: Removes an item from the stack. The items are popped in the reversed order
in which they are pushed. If the stack is empty, then it is said to be an Underflow
condition.
• Peek or Top: Returns top element of stack.
• isEmpty: Returns true if stack is empty, else false.
1459
Chapter 247. Stack Data Structure (Introduction and Program)
• Balancing of symbols
• Infix to Postfix /Prefix conversion
• Redo-undo features at many places like editors, photoshop.
• Forward and backward feature in web browsers
• Used in many algorithms like Tower of Hanoi, tree traversals, stock span problem,
histogram problem.
• Other applications can be Backtracking, Knight tour problem, rat in a maze,N queen
problem and sudoku solver
• In Graph Algorithms like Topological Sorting and Strongly Connected Components
Implementation:
There are two ways to implement a stack:
• Using array
• Using linked list
1460
Chapter 247. Stack Data Structure (Introduction and Program)
class Stack
{
int top;
public:
int a[MAX]; //Maximum size of Stack
bool Stack::push(int x)
{
if (top >= (MAX-1))
{
cout << "Stack Overflow";
return false;
}
else
{
a[++top] = x;
cout<<x <<" pushed into stack\n";
return true;
}
}
int Stack::pop()
{
if (top < 0)
{
cout << "Stack Underflow";
return 0;
}
else
{
int x = a[top--];
return x;
}
}
1461
Chapter 247. Stack Data Structure (Introduction and Program)
bool Stack::isEmpty()
{
return (top < 0);
}
return 0;
}
1462
Chapter 247. Stack Data Structure (Introduction and Program)
push(stack, 10);
push(stack, 20);
push(stack, 30);
return 0;
}
Java
boolean isEmpty()
{
return (top < 0);
}
1463
Chapter 247. Stack Data Structure (Introduction and Program)
Stack()
{
top = -1;
}
boolean push(int x)
{
if (top >= (MAX-1))
{
System.out.println("Stack Overflow");
return false;
}
else
{
a[++top] = x;
System.out.println(x + " pushed into stack");
return true;
}
}
int pop()
{
if (top < 0)
{
System.out.println("Stack Underflow");
return 0;
}
else
{
int x = a[top--];
return x;
}
}
}
// Driver code
class Main
{
public static void main(String args[])
{
Stack s = new Stack();
s.push(10);
s.push(20);
s.push(30);
System.out.println(s.pop() + " Popped from stack");
}
}
1464
Chapter 247. Stack Data Structure (Introduction and Program)
Python
return stack.pop()
C#
namespace ImplementStack
{
class Stack
{
private int[] ele;
1465
Chapter 247. Stack Data Structure (Introduction and Program)
1466
Chapter 247. Stack Data Structure (Introduction and Program)
}
}
}
}
p.push(10);
p.push(20);
p.push(30);
p.printStack();
p.pop();
}
}
}
1467
Chapter 247. Stack Data Structure (Introduction and Program)
{
struct StackNode* stackNode =
(struct StackNode*) malloc(sizeof(struct StackNode));
stackNode->data = data;
stackNode->next = NULL;
return stackNode;
}
return popped;
}
int main()
{
struct StackNode* root = NULL;
push(&root, 10);
push(&root, 20);
push(&root, 30);
1468
Chapter 247. Stack Data Structure (Introduction and Program)
return 0;
}
Python
class Stack:
def isEmpty(self):
return True if self.root is None else False
def pop(self):
if (self.isEmpty()):
return float("-inf")
temp = self.root
self.root = self.root.next
popped = temp.data
return popped
def peek(self):
if self.isEmpty():
return float("-inf")
return self.root.data
1469
Chapter 247. Stack Data Structure (Introduction and Program)
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
Output:
10 pushed to stack
20 pushed to stack
30 pushed to stack
30 popped from stack
Top element is 20
Pros: The linked list implementation of stack can grow and shrink according to the needs
at runtime.
Cons: Requires extra memory due to involvement of pointers.
Source
https://www.geeksforgeeks.org/stack-data-structure-introduction-program/
1470
Chapter 248
Algorithm:
1- Take first node of second list.
2- Start matching the first list from this first node.
3- If whole lists match return true.
4- Else break and take first list to the first node again.
5- And take second list to its second node.
6- Repeat these steps until any of linked lists becomes empty.
7- If first list becomes empty then list found else not.
Below is C++ implementation.
1471
Chapter 248. Sublist Search (Search a linked list in another list)
#include <bits/stdc++.h>
using namespace std;
1472
Chapter 248. Sublist Search (Search a linked list in another list)
return false;
}
1473
Chapter 248. Sublist Search (Search a linked list in another list)
a->next->next = newNode(3);
a->next->next->next = newNode(4);
Node *b = newNode(1);
b->next = newNode(2);
b->next->next = newNode(1);
b->next->next->next = newNode(2);
b->next->next->next->next = newNode(3);
b->next->next->next->next->next = newNode(4);
return 0;
}
Output:
LIST FOUND
Time Complexity : O(m*n) where m is the number of nodes in second list and n in first.
Optimization :
Above code can be optimized by using extra space i.e. stores the list into two strings
and apply KMP algorithm. Refer https://ide.geeksforgeeks.org/3fXUaV for implementation
provided by Nishant Singh.
Source
https://www.geeksforgeeks.org/sublist-search-search-a-linked-list-in-another-list/
1474
Chapter 249
C++
1475
Chapter 249. Subtract Two Numbers represented as Linked Lists
1476
Chapter 249. Subtract Two Numbers represented as Linked Lists
temp->next = sNode;
return zHead;
}
int d1 = l1->data;
int d2 = l2->data;
int sub = 0;
return current;
}
1477
Chapter 249. Subtract Two Numbers represented as Linked Lists
else
{
// If both list lengths are equal, then calculate
// the larger and smaller list. If 5-6-7 & 5-6-8
// are linked list, then walk through linked list
// at last Node as 7 < 8, larger Node is 5-6-8
// and smaller Node is 5-6-7.
while (l1 && l2)
{
if (l1->data != l2->data)
{
lNode = l1->data > l2->data ? temp1 : temp2;
sNode = l1->data > l2->data ? temp2 : temp1;
break;
}
l1 = l1->next;
l2 = l2->next;
}
}
1478
Chapter 249. Subtract Two Numbers represented as Linked Lists
printList(result);
return 0;
}
Java
class LinkedList
{
static Node head; // head of list
boolean borrow;
1479
Chapter 249. Subtract Two Numbers represented as Linked Lists
/* Node Class */
static class Node {
int data;
Node next;
1480
Chapter 249. Subtract Two Numbers represented as Linked Lists
int d1 = l1.data;
int d2 = l2.data;
int sub = 0;
return current;
}
1481
Chapter 249. Subtract Two Numbers represented as Linked Lists
{
// Base Case.
if (l1 == null && l2 == null)
return null;
else
{
// If both list lengths are equal, then
// calculate the larger and smaller list.
// If 5-6-7 & 5-6-8 are linked list, then
// walk through linked list at last Node
// as 7 < 8, larger Node is 5-6-8 and
// smaller Node is 5-6-7.
while (l1 != null && l2 != null)
{
if (l1.data != l2.data)
{
lNode = l1.data > l2.data ? temp1 : temp2;
sNode = l1.data > l2.data ? temp2 : temp1;
break;
}
l1 = l1.next;
l2 = l2.next;
}
}
1482
Chapter 249. Subtract Two Numbers represented as Linked Lists
printList(result);
}
}
Output :
0 9 9
Source
https://www.geeksforgeeks.org/subtract-two-numbers-represented-as-linked-lists/
1483
Chapter 250
• Consider nodes in groups of size k. In every group, replace value of first node with
group sum.
• Also, delete the elements of group except the first node.
• During traversal, if the remaining nodes in linked list are less than k then also do the
above considering remaining nodes.
Examples:
Input: N = 6, K = 2
1->2->3->4->5->6
Output: 3 7 11
We have denoted grouping of k elements by (). The elements inside () are
summed.
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null
(1 -> 2) -> 3 -> 4 -> 5 -> 6 -> null
(3) -> 3 -> 4 -> 5 -> 6 -> null
3 -> (3 -> 4) -> 5 -> 6 -> null
3 -> (7) -> 5 -> 6 -> null
3 -> 7 -> (5 -> 6) -> null
3 -> 7 -> (11) -> null
3 -> 7 -> 11 -> null
Approach: Insert the given nodes in the Linked list. The approach of insertion has been
discussed in this post. Once the nodes are inserted, iterate from the beginning of the list.
Mark the first node as temp node. Iterate for the next k-1 nodes and sum up the nodes
in sum variable. If the number of nodes is less than K, then replace the temp node’s data
1484
Chapter 250. Sudo Placement[1.4] | K Sum
with sum and point temp to NULL. If there is a group with K nodes, replace the temp’s
data with sum and move temp to the node which is just after K nodes. Continue the above
operation till temp points to NULL. Once temp reaches the end, it means all groups of size
K has been traversed and the node has been replaced with the sum of nodes of size K. Once
the operation of replacements have been done, the linked list thus formed can be printed.
The method of printing the linked list has been discussed in this post.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
return head;
}
1485
Chapter 250. Sudo Placement[1.4] | K Sum
while (head) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
// summation of nodes
long long sum = 0;
// Driver Code
1486
Chapter 250. Sudo Placement[1.4] | K Sum
int main()
{
int k = 2;
// Function call to perform the
// given operations
KSum(head, k);
return 0;
}
Java
import java.io.*;
import java.util.*;
class GFG
{
1487
Chapter 250. Sudo Placement[1.4] | K Sum
return head;
}
// function to perform
// the following operation
public static void KSum(Node head, int k)
{
// initially pointing
// to start
Node temp = head;
// dummy variable
// to store k
int count = k;
// summation of nodes
int sum = 0;
1488
Chapter 250. Sudo Placement[1.4] | K Sum
// move temp to
// next pointer
temp.next = curr;
// move temp to
// the next pointer
temp = temp.next;
}
//return temp;
}
// Driver Code
public static void main(String args[])
{
head = null;
// inserts nodes in
// the linked list
head = insertNode(head, 1);
head = insertNode(head, 2);
head = insertNode(head, 3);
head = insertNode(head, 4);
head = insertNode(head, 5);
head = insertNode(head, 6);
int k = 2;
1489
Chapter 250. Sudo Placement[1.4] | K Sum
KSum(head, k);
Output:
3 7 11
Source
https://www.geeksforgeeks.org/sudo-placement1-4-k-sum/
1490
Chapter 251
Task is to do A + B + C + D.
Examples:
Input: 7->6->8->4->1
Output: 26
Sum of nodes:
7 + 6 + 8 + 4 + 1 = 26
Input: 1->7->3->9->11->5
Output: 36
Recursive Solution:
1491
Chapter 251. Sum of the nodes of a Singly Linked List
• Call a function by passing the head and variable to store the sum.
– Then recursively call the function by passing the next of current node and sum
variable.
* Add the value of the current node to the sum.
// accumulate sum
1492
Chapter 251. Sum of the nodes of a Singly Linked List
int sum = 0;
// required sum
return sum;
}
Output:
Sum of nodes = 26
1. Initialise a pointer ptr with the head of the linked list and a sum variable with 0.
2. Start traversing the linked list using a loop until all the nodes get traversed.
• Add the value of current node to the sum i.e. sum += ptr -> data .
• Increment the pointer to the next node of linked list i.e. ptr = ptr ->next .
1493
Chapter 251. Sum of the nodes of a Singly Linked List
sum += ptr->data;
ptr = ptr->next;
}
return sum;
}
1494
Chapter 251. Sum of the nodes of a Singly Linked List
int main()
{
struct Node* head = NULL;
Output:
Sum of nodes = 26
Source
https://www.geeksforgeeks.org/sum-of-the-nodes-of-a-singly-linked-list/
1495
Chapter 252
Swap Kth node from beginning with Kth node from end in a Linked List - GeeksforGeeks
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping
of data is not allowed, only pointers should be changed. This requirement may be
logical in many situations where the linked list data part is huge (For example student
details line Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most
of the compilers).
The problem seems simple at first look, but it has many interesting cases.
Let X be the kth node from beginning and Y be the kth node from end. Following are the
interesting cases that must be handled.
1) Y is next to X
2) X is next to Y
3) X and Y are same
4) X and Y don’t exist (k is more than number of nodes in linked list)
C++
// A C++ program to swap Kth node from beginning with kth node from end
#include <iostream>
#include <stdlib.h>
using namespace std;
1496
Chapter 252. Swap Kth node from beginning with Kth node from end in a Linked List
};
/* Function for swapping kth nodes from both ends of linked list */
void swapKth(struct Node **head_ref, int k)
{
// Count nodes in linked list
int n = countNodes(*head_ref);
// Check if k is valid
if (n < k) return;
// If x (kth node from start) and y(kth node from end) are same
if (2*k - 1 == n) return;
// Find the kth node from beginning of linked list. We also find
// previous of kth node because we need to update next pointer of
1497
Chapter 252. Swap Kth node from beginning with Kth node from end in a Linked List
// the previous.
Node *x = *head_ref;
Node *x_prev = NULL;
for (int i = 1; i < k; i++)
{
x_prev = x;
x = x->next;
}
// Similarly, find the kth node from end and its previous. kth node
// from end is (n-k+1)th node from beginning
Node *y = *head_ref;
Node *y_prev = NULL;
for (int i = 1; i < n-k+1; i++)
{
y_prev = y;
y = y->next;
}
1498
Chapter 252. Swap Kth node from beginning with Kth node from end in a Linked List
return 0;
}
Java
class Node
{
int data;
Node next;
Node(int d) { data = d; next = null; }
}
class LinkedList
{
Node head;
1499
Chapter 252. Swap Kth node from beginning with Kth node from end in a Linked List
node = node.next;
}
System.out.println("");
}
// Check if k is valid
if (n < k)
return;
1500
Chapter 252. Swap Kth node from beginning with Kth node from end in a Linked List
Node y = head;
Node y_prev = null;
for (int i = 1; i < n - k + 1; i++)
{
y_prev = y;
y = y.next;
}
if (k == n)
head = x;
}
1501
Chapter 252. Swap Kth node from beginning with Kth node from end in a Linked List
llist.swapKth(i);
System.out.println("Modified List for k = " + i);
llist.printList();
System.out.println("");
}
}
}
Output:
Please note that the above code runs three separate loops to count nodes, find x and x prev,
and to find y and y_prev. These three things can be done in a single loop. The code uses
three loops to keep things simple and readable.
Thanks to Chandra Prakash for initial solution. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/swap-kth-node-from-beginning-with-kth-node-from-end-in-a-linked-list/
1502
Chapter 253
This may look a simple problem, but is interesting question as it has following cases to be
handled.
1) x and y may or may not be adjacent.
2) Either x or y may be a head node.
3) Either x or y may be last node.
4) x and/or y may not be present in linked list.
How to write a clean working code that handles all of the above possibilities.
We strongly recommend to minimize your browser and try this yourself first.
1503
Chapter 253. Swap nodes in a linked list without swapping data
The idea it to first search x and y in given linked list. If any of them is not present, then
return. While searching for x and y, keep track of current and previous pointers. First
change next of previous pointers, then change next of current pointers. Following are C and
Java implementations of this approach.
C
#include<stdio.h>
#include<stdlib.h>
1504
Chapter 253. Swap nodes in a linked list without swapping data
prevX->next = currY;
else // Else make y as new head
*head_ref = currY;
1505
Chapter 253. Swap nodes in a linked list without swapping data
swapNodes(&start, 4, 3);
return 0;
}
Java
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
class LinkedList
{
Node head; // head of list
1506
Chapter 253. Swap nodes in a linked list without swapping data
1507
Chapter 253. Swap nodes in a linked list without swapping data
llist.swapNodes(4, 3);
Python
# head of list
1508
Chapter 253. Swap nodes in a linked list without swapping data
class Node(object):
def __init__(self, d):
self.data = d
self.next = None
1509
Chapter 253. Swap nodes in a linked list without swapping data
Output:
Optimizations: The above code can be optimized to search x and y in single traversal.
Two loops are used to keep program simple.
Simpler approach –
1510
Chapter 253. Swap nodes in a linked list without swapping data
#include <iostream>
public:
int data;
class Node* next;
// constructor
Node(int val, Node* next)
: data(val), next(next)
{
}
// allocate node
(*head_ref) = new Node(new_data, *head_ref);
}
Node* temp = a;
a = b;
1511
Chapter 253. Swap nodes in a linked list without swapping data
b = temp;
}
if ((*head_ref)->data == x) {
a = head_ref;
}
else if ((*head_ref)->data == y) {
b = head_ref;
}
head_ref = &((*head_ref)->next);
}
swap(*a, *b);
swap(((*a)->next), ((*b)->next));
}
}
int main()
{
1512
Chapter 253. Swap nodes in a linked list without swapping data
push(&start, 3);
push(&start, 2);
push(&start, 1);
swapNodes(&start, 6, 3);
Output:
This article is contributed by Gautam. Please write comments if you find anything incor-
rect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/swap-nodes-in-a-linked-list-without-swapping-data/
1513
Chapter 254
Source
https://www.geeksforgeeks.org/the-great-tree-list-recursion-problem/
1514
Chapter 255
Input:
List1: 10->15->4->20
lsit2: 8->4->2->10
Output:
Intersection List: 4->10
Union List: 2->8->20->4->15->10
Method 1 (Simple)
Following are simple algorithms to get union and intersection lists respectively.
Intersection (list1, list2)
Initialize result list as NULL. Traverse list1 and look for its each element in list2, if the
element is present in list2, then add the element to result.
Union (list1, list2):
Initialize result list as NULL. Traverse list1 and add all of its elements to the result.
Traverse list2. If an element of list2 is already present in result then do not insert it to
result, otherwise insert.
This method assumes that there are no duplicates in the given lists.
Thanks to Shekhu for suggesting this method. Following are C and Java implementations
of this method.
1515
Chapter 255. Union and Intersection of two Linked Lists
C/C++
return result;
}
1516
Chapter 255. Union and Intersection of two Linked Lists
return result;
}
1517
Chapter 255. Union and Intersection of two Linked Lists
1518
Chapter 255. Union and Intersection of two Linked Lists
return 0;
}
Java
1519
Chapter 255. Union and Intersection of two Linked Lists
1520
Chapter 255. Union and Intersection of two Linked Lists
return true;
t = t.next;
}
return false;
}
intersecn.getIntersection(llist1.head, llist2.head);
unin.getUnion(llist1.head, llist2.head);
Output:
First list is
1521
Chapter 255. Union and Intersection of two Linked Lists
10 15 4 20
Second list is
8 4 2 10
Intersection list is
4 10
Union list is
2 8 20 4 15 10
Time Complexity: O(mn) for both union and intersection operations. Here m is the number
of elements in first list and n is the number of elements in second list.
Method 2 (Use Merge Sort)
In this method, algorithms for Union and Intersection are very similar. First we sort the
given lists, then we traverse the sorted lists to get union and intersection.
Following are the steps to be followed to get union and intersection lists.
1) Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this
post for details of this step.
2) Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this
post for details of this step.
3) Linearly scan both sorted lists to get the union and intersection. This step takes O(m +
n) time. This step can be implemented using the same algorithm as sorted arrays algorithm
discussed here.
Time complexity of this method is O(mLogm + nLogn) which is better than method 1’s
time complexity.
Method 3 (Use Hashing)
Union (list1, list2)
Initialize the result list as NULL and create an empty hash table. Traverse both lists one
by one, for each element being visited, look the element in hash table. If the element is not
present, then insert the element to result list. If the element is present, then ignore it.
Intersection (list1, list2)
Initialize the result list as NULL and create an empty hash table. Traverse list1. For each
element being visited in list1, insert the element in hash table. Traverse list2, for each
element being visited in list2, look the element in hash table. If the element is present, then
insert the element to result list. If the element is not present, then ignore it.
Both of the above methods assume that there are no duplicates.
class LinkedList {
Node head; // head of list
1522
Chapter 255. Union and Intersection of two Linked Lists
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
1523
Chapter 255. Union and Intersection of two Linked Lists
n1 = n1.next;
}
n1.next = n2;
n2.next = null;
}
1524
Chapter 255. Union and Intersection of two Linked Lists
result.push(n2.data);
}
n2 = n2.next;
}
return result;
}
1525
Chapter 255. Union and Intersection of two Linked Lists
intersection = intersection.getIntersection(llist1.head,
llist2.head);
union=union.getUnion(llist1.head, llist2.head);
1526
Chapter 255. Union and Intersection of two Linked Lists
Output:
First List is
10 15 4 20
Second List is
8 4 2 10
Intersection List is
10 4
Union List is
2 4 20 8 10 15
Time complexity of this method depends on the hashing technique used and the distribution
of elements in input lists. In practical, this approach may turn out to be better than above
2 methods.
Source
https://www.geeksforgeeks.org/union-and-intersection-of-two-linked-lists/
1527
Chapter 256
Union and Intersection of two linked lists | Set-2 (Using Merge Sort) - GeeksforGeeks
Given two Linked Lists, create union and intersection lists that contain union and inter-
section of the elements present in the given lists. Order of elements in output lists doesn’t
matter.
Examples:
Input:
List1: 10 -> 15 -> 4 ->20
lsit2: 8 -> 4 -> 2 -> 10
Output:
Intersection List: 4 -> 10
Union List: 2 -> 8 -> 20 -> 4 -> 15 -> 10
There were three methods discussed in this post with an implementation of Method 1.
In this post, we will see an implementation of Method 2 i.e. Using Merge sort.
Implementation:
Following are the steps to be followed to get union and intersection lists.
2) Linearly scan both sorted lists to get the union and intersection.
This step takes O(m + n) time.
1528
Chapter 256. Union and Intersection of two linked lists | Set-2 (Using Merge Sort)
Just like Method 1, This method also assumes that there are distinct elements in the lists.
/* UTILITY FUNCTIONS */
/* Split the nodes of the given list into front and back halves,
and return the two lists using the reference parameters.
If the length is odd, the extra node should go in the front list.
Uses the fast/slow pointer strategy. */
void FrontBackSplit(struct Node* source, struct Node** frontRef,
struct Node** backRef)
{
struct Node* fast;
struct Node* slow;
if (source==NULL || source->next==NULL)
{
/* length < 2 cases */
*frontRef = source;
*backRef = NULL;
}
1529
Chapter 256. Union and Intersection of two linked lists | Set-2 (Using Merge Sort)
else
{
slow = source;
fast = source->next;
/* Base cases */
if (a == NULL)
return(b);
else if (b==NULL)
return(a);
1530
Chapter 256. Union and Intersection of two linked lists | Set-2 (Using Merge Sort)
1531
Chapter 256. Union and Intersection of two linked lists | Set-2 (Using Merge Sort)
return result;
}
1532
Chapter 256. Union and Intersection of two linked lists | Set-2 (Using Merge Sort)
else
{
// Store current element in the list
push(&result, t2->data);
1533
Chapter 256. Union and Intersection of two linked lists | Set-2 (Using Merge Sort)
return 0;
}
Output:
First list is
4 10 11 15 20
Second list is
2 4 8 10
Intersection list is
10 4
Union list is
20 15 11 10 8 4 2
Source
https://www.geeksforgeeks.org/union-intersection-two-linked-lists-set-2-using-merge-sort/
1534
Chapter 257
Input:
List1: 10 -> 15 -> 4 -> 20
list2: 8 -> 4 -> 2 -> 10
Output:
Intersection List: 4 -> 10
Union List: 2 -> 8 -> 20 -> 4 -> 15 -> 10
Implementation:
1- Start traversing both the lists.
a) Store the current element of both lists
with its occurrence in the map.
2- For Union: Store all the elements of the map
in the resultant list.
3- For Intersection: Store all the elements only
with an occurrence of 2 as 2 denotes that
they are present in both the lists.
1535
Chapter 257. Union and Intersection of two linked lists | Set-3 (Hashing)
1536
Chapter 257. Union and Intersection of two linked lists | Set-3 (Hashing)
return result;
}
1537
Chapter 257. Union and Intersection of two linked lists | Set-3 (Hashing)
printUnionIntersection(head1, head2);
1538
Chapter 257. Union and Intersection of two linked lists | Set-3 (Hashing)
return 0;
}
Output:
First list is
5 4 3 2 1
Second list is
6 5 3 1
Intersection list is
3 5 1
Union list is
3 4 6 5 2 1
We can also handle the case of duplicates by maintaining separate Hash for both the lists.
Time Complexity : O(m + n)
Auxiliary Space : O(m + n)
Source
https://www.geeksforgeeks.org/union-intersection-two-linked-lists-set-3-hashing/
1539
Chapter 258
Advantages:
1540
Chapter 258. Unrolled Linked List | Set 1 (Introduction)
• Because of the Cache behavior, linear search is much faster in unrolled linked lists.
• In comparison to ordinary linked list, it requires less storage space for point-
ers/references.
• It performs operations like insertion, deletion and traversal more quickly than ordinary
linked lists (because search is faster).
Disadvantages:
• The overhead per node is comparatively high than singly linked lists. Refer an example
node in below code.
Simple Implementation in C
The below program creates a simple unrolled linked list with 3 nodes containing variable
number of elements in each. It also traverses the created list.
1541
Chapter 258. Unrolled Linked List | Set 1 (Introduction)
{
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
// allocate 3 Nodes
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
printUnrolledList(head);
return 0;
}
Output:
1542
Chapter 258. Unrolled Linked List | Set 1 (Introduction)
1 2 3 4 5 6 7 8 9
In this article, we have introduced unrolled list and advantages of it. We have also shown
how to traverse the list. In the next article, we will be discussing insertion, deletion and
values of maxElements/numElements in detail.
Insertion in Unrolled Linked List
Source
https://www.geeksforgeeks.org/unrolled-linked-list-set-1-introduction/
1543
Chapter 259
Write a function that counts the number of times a given int occurs in a Linked List -
GeeksforGeeks
Given a singly linked list and a key, count number of occurrences of given key in linked list.
For example, if given linked list is 1->2->1->2->1->3->1 and given key is 1, then output
should be 4.
Method 1- Without Recursion
Algorithm:
Implementation:
C/C++
1544
Chapter 259. Write a function that counts the number of times a given int occurs in a
Linked List
{
int data;
struct Node* next;
};
1545
Chapter 259. Write a function that counts the number of times a given int occurs in a
Linked List
push(&head, 3);
push(&head, 1);
push(&head, 2);
push(&head, 1);
Java
1546
Chapter 259. Write a function that counts the number of times a given int occurs in a
Linked List
count++;
current = current.next;
}
return count;
}
Python
# Node class
class Node:
class LinkedList:
1547
Chapter 259. Write a function that counts the number of times a given int occurs in a
Linked List
count = 0
while(current is not None):
if current.data == search_for:
count += 1
current = current.next
return count
# Driver program
llist = LinkedList()
llist.push(1)
llist.push(3)
llist.push(1)
llist.push(2)
llist.push(1)
Output:
count of 1 is 3
Algorithm
count(head,key);
if head is NULL
1548
Chapter 259. Write a function that counts the number of times a given int occurs in a
Linked List
return frequency
if(head->data==key)
increase frequency by 1
count(head->next,key)
Implementation:
C++
1549
Chapter 259. Write a function that counts the number of times a given int occurs in a
Linked List
if (head->data == key)
frequency++;
return count(head->next, key);
}
Output:
count of 1 is 3
The above method implements head recursion. Below given is the tail recursive implemen-
tation for the same. Thanks to Puneet Jain for suggesting this approach :
// else
return frequency;
}
1550
Chapter 259. Write a function that counts the number of times a given int occurs in a
Linked List
Source
https://www.geeksforgeeks.org/write-a-function-that-counts-the-number-of-times-a-given-int-occurs-in-a-linked-lis
1551
Chapter 260
C/C++
1552
Chapter 260. Write a function to delete a Linked List
1553
Chapter 260. Write a function to delete a Linked List
Java
llist.push(1);
llist.push(4);
llist.push(1);
1554
Chapter 260. Write a function to delete a Linked List
llist.push(12);
llist.push(1);
Python3
# Node class
class Node:
def deleteList(self):
1555
Chapter 260. Write a function to delete a Linked List
llist = LinkedList()
llist.push(1)
llist.push(4)
llist.push(1)
llist.push(12)
llist.push(1)
Output:
Source
https://www.geeksforgeeks.org/write-a-function-to-delete-a-linked-list/
1556
Chapter 261
Example:
Algorithm:
1. Initialize count = 0
2. Loop through the link list
a. if count is equal to the passed index then return current
node
b. Increment count
c. change current to point to next of the current.
Implementation:
1557
Chapter 261. Write a function to get Nth node in a Linked List
// allocate node
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
1558
Chapter 261. Write a function to get Nth node in a Linked List
// looking at
int count = 0;
while (current != NULL)
{
if (count == index)
return(current->data);
count++;
current = current->next;
}
// Driver Code
int main()
{
Java
class Node
{
int data;
1559
Chapter 261. Write a function to get Nth node in a Linked List
Node next;
Node(int d)
{
data = d;
next = null;
}
}
class LinkedList
{
Node head; //the head of list
1560
Chapter 261. Write a function to get Nth node in a Linked List
Python
# Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
1561
Chapter 261. Write a function to get Nth node in a Linked List
new_node.next = self.head
llist = LinkedList()
n = 3
print ("Element at index 3 is :", llist.getNth(n))
Output:
Element at index 3 is 4
1562
Chapter 261. Write a function to get Nth node in a Linked List
Algorithm
getnth(node,n)
1. Initialize count = 1
2. if count==n
return node->data
3. else
return getnth(node->next,n-1)
Implementation:
C++
1563
Chapter 261. Write a function to get Nth node in a Linked List
Output:
Element at index 3 is 1
Source
https://www.geeksforgeeks.org/write-a-function-to-get-nth-node-in-a-linked-list/
1564
Chapter 262
Write a function to get the intersection point of two Linked Lists. - GeeksforGeeks
There are two singly linked lists in a system. By some programming error, the end node of
one of the linked list got linked to the second list, forming an inverted Y shaped list. Write
a program to get the point where two linked list merge.
Above diagram shows an example with two linked list having 15 as intersection point.
Method 1(Simply use two loops)
Use 2 nested for loops. The outer loop will be for each node of the 1st list and inner loop
1565
Chapter 262. Write a function to get the intersection point of two Linked Lists.
will be for 2nd list. In the inner loop, check if any of nodes of the 2nd list is same as the
current node of the first linked list. The time complexity of this method will be O(mn)
where m and n are the numbers of nodes in two lists.
Method 2 (Mark Visited Nodes)
This solution requires modifications to basic linked list data structure. Have a visited
flag with each node. Traverse the first linked list and keep marking visited nodes. Now
traverse the second linked list, If you see a visited node again then there is an intersection
point, return the intersecting node. This solution works in O(m+n) but requires additional
information with each node. A variation of this solution that doesn’t require modification
to the basic data structure can be implemented using a hash. Traverse the first linked list
and store the addresses of visited nodes in a hash. Now traverse the second linked list and
if you see an address that already exists in the hash then return the intersecting node.
Method 3(Using difference of node counts)
1) Get count of the nodes in the first list, let count be c1.
2) Get count of the nodes in the second list, let count be c2.
3) Get the difference of counts d = abs(c1 – c2)
4) Now traverse the bigger list from the first node till d nodes so that from here onwards
both the lists have equal no of nodes.
5) Then we can traverse both the lists in parallel till we come across a common node. (Note
that getting a common node is done by comparing the address of the nodes)
C
#include<stdio.h>
#include<stdlib.h>
1566
Chapter 262. Write a function to get the intersection point of two Linked Lists.
int d;
return -1;
}
1567
Chapter 262. Write a function to get the intersection point of two Linked Lists.
return count;
}
1st 3->6->9->15->30
2nd 10->15->30
1568
Chapter 262. Write a function to get the intersection point of two Linked Lists.
head1->next->next->next = NULL;
getchar();
}
Java
class LinkedList {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
1569
Chapter 262. Write a function to get the intersection point of two Linked Lists.
return -1;
}
return count;
}
1570
Chapter 262. Write a function to get the intersection point of two Linked Lists.
}
}
1) Let X be the length of the first linked list until intersection point.
Let Y be the length of the second linked list until the intersection point.
Let Z be the length of the linked list from the intersection point to End of
the linked list including the intersection node.
We Have
X + Z = C1;
Y + Z = C2;
2) Reverse first linked list.
3) Traverse Second linked list. Let C3 be the length of second list - 1.
Now we have
X + Y = C3
We have 3 linear equations. By solving them, we get
X = (C1 + C3 – C2)/2;
Y = (C2 + C3 – C1)/2;
Z = (C1 + C2 – C3)/2;
WE GOT THE INTERSECTION POINT.
4) Reverse first linked list.
1571
Chapter 262. Write a function to get the intersection point of two Linked Lists.
The time complexity of this method is O(m+n) and used Auxiliary space is O(1)
Method 7 (Use Hashing)
Basically, we need to find a common node of two linked lists. So we hash all nodes of the
first list and then check the second list.
1) Create an empty hash table such that node address is used as key and a binary value
present/absent is used as the value.
2) Traverse the first linked list and insert all nodes’ addresses in the hash table.
3) Traverse the second list. For every node check if it is present in the hash table. If we find
a node in the hash table, return the node.
Please write comments if you find any bug in the above algorithm or a better way to solve
the same problem.
Source
https://www.geeksforgeeks.org/write-a-function-to-get-the-intersection-point-of-two-linked-lists/
1572
Chapter 263
XOR Linked List - A Memory Efficient Doubly Linked List | Set 1 - GeeksforGeeks
An ordinary Doubly Linked List requires space for two address fields to store the addresses
of previous and next nodes. A memory efficient version of Doubly Linked List can be created
using only one space for address field with every node. This memory efficient Doubly Linked
List is called XOR Linked List or Memory Efficient as the list uses bitwise XOR operation
to save space for one address. In the XOR linked list, instead of storing actual memory
addresses, every node stores the XOR of addresses of previous and next nodes.
Consider the above Doubly Linked List. Following are the Ordinary and XOR (or Memory
Effiecient) representations of the Doubly Linked List.
Ordinary Representation:
Node A:
prev = NULL, next = add(B) // previous is NULL and next is address of B
Node B:
prev = add(A), next = add(C) // previous is address of A and next is address of C
Node C:
prev = add(B), next = add(D) // previous is address of B and next is address of D
1573
Chapter 263. XOR Linked List – A Memory Efficient Doubly Linked List | Set 1
Node D:
prev = add(C), next = NULL // previous is address of C and next is NULL
XOR List Representation:
Let us call the address variable in XOR representation npx (XOR of next and previous)
Node A:
npx = 0 XOR add(B) // bitwise XOR of zero and address of B
Node B:
npx = add(A) XOR add(C) // bitwise XOR of address of A and address of C
Node C:
npx = add(B) XOR add(D) // bitwise XOR of address of B and address of D
Node D:
npx = add(C) XOR 0 // bitwise XOR of address of C and 0
Traversal of XOR Linked List:
We can traverse the XOR list in both forward and reverse direction. While traversing the
list we need to remember the address of the previously accessed node in order to calculate
the next node’s address. For example when we are at node C, we must have address of B.
XOR of add(B) and npx of C gives us the add(D). The reason is simple: npx(C) is “add(B)
XOR add(D)”. If we do xor of npx(C) with add(B), we get the result as “add(B) XOR
add(D) XOR add(B)” which is “add(D) XOR 0” which is “add(D)”. So we have the address
of next node. Similarly we can traverse the list in backward direction.
We have covered more on XOR Linked List in the following post.
XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
References:
http://en.wikipedia.org/wiki/XOR_linked_list
http://www.linuxjournal.com/article/6828?page=0,0
Source
https://www.geeksforgeeks.org/xor-linked-list-a-memory-efficient-doubly-linked-list-set-1/
1574
Chapter 264
XOR Linked List – A Memory Efficient Doubly Linked List | Set 2 - GeeksforGeeks
In the previous post, we discussed how a Doubly Linked can be created using only one space
for address field with every node. In this post, we will discuss implementation of memory
efficient doubly linked list. We will mainly discuss following two simple functions.
1) A function to insert a new node at the beginning.
2) A function to traverse the list in forward direction.
In the following code, insert() function inserts a new node at the beginning. We need to
change the head pointer of Linked List, that is why a double pointer is used (See this). Let
use first discuss few things again that have been discussed in the previous post. We store
XOR of next and previous nodes with every node and we call it npx, which is the only
address member we have with every node. When we insert a new node at the beginning,
npx of new node will always be XOR of NULL and current head. And npx of current head
must be changed to XOR of new node and node next to current head.
printList() traverses the list in forward direction. It prints data values from every node. To
traverse the list, we need to get pointer to the next node at every point. We can get the
address of next node by keeping track of current node and previous node. If we do XOR of
curr->npx and prev, we get the address of next node.
1575
Chapter 264. XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
// Change head
*head_ref = new_node;
}
1576
Chapter 264. XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
return (0);
}
Output:
Note that XOR of pointers is not defined by C/C++ standard. So the above implementation
may not work on all platforms.
Improved By : piyush02
1577
Chapter 264. XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
Source
https://www.geeksforgeeks.org/xor-linked-list-a-memory-efficient-doubly-linked-list-set-2/
1578