Contents
1 A Programmer’s approach of looking at Array vs. Linked List 17
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2 Add 1 to a number represented as linked list 22
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3 Add two numbers represented by linked lists | Set 1 28
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
4 Add two numbers represented by linked lists | Set 2 37
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
5 Adding two polynomials using Linked List 47
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
6 Alternate Odd and Even Nodes in a Singly Linked List 52
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
7 Alternate sorting of Linked list 60
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
8 Alternating split of a given Singly Linked List | Set 1 66
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
9 An interesting method to print reverse of a linked list 71
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
10 Applications of linked list data structure 75
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
11 Arrange consonants and vowels nodes in a linked list 77
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
12 Binary Search on Singly Linked List 83
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
13 Brent’s Cycle Detection Algorithm 87
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
1
Contents
14 Bubble Sort On Doubly Linked List 94
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
15 C Program for Bubble Sort on Linked List 98
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
16 C Program to reverse each node value in Singly Linked List 102
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
17 Can we reverse a linked list in less than O(n)? 105
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
18 Check if a doubly linked list of characters is palindrome or not 106
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
19 Check if a linked list is Circular Linked List 109
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
20 Check if a linked list of strings forms a palindrome 112
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
21 Check if linked list is sorted (Iterative and Recursive) 118
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
22 Check linked list with a loop is palindrome or not 122
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
23 Check whether the length of given linked list is Even or Odd 127
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
24 Circular Linked List | Set 1 (Introduction and Applications) 130
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
25 Circular Linked List | Set 2 (Traversal) 132
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
26 Circular Queue | Set 2 (Circular Linked List Implementation) 137
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
27 Circular Singly Linked List | Insertion 139
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
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
31 Compare two strings represented as linked lists 164
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
32 Construct a Maximum Sum Linked List out of two Sorted Linked Lists
having some Common nodes 170
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
33 Construct a linked list from 2D matrix 181
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
34 Construct a linked list from 2D matrix (Iterative Approach) 186
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
35 Convert a Binary Tree to a Circular Doubly Link List 191
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
36 Convert a given Binary Tree to Doubly Linked List | Set 1 199
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
37 Convert a given Binary Tree to Doubly Linked List | Set 2 208
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
38 Convert a given Binary Tree to Doubly Linked List | Set 3 217
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
39 Convert a given Binary Tree to Doubly Linked List | Set 4 223
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
40 Convert singly linked list into circular linked list 229
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
41 Count nodes in Circular linked list 232
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
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
44 Count rotations in sorted and rotated linked list 256
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
45 Count triplets in a sorted doubly linked list whose sum is equal to a
given value x 259
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
46 Create a Doubly Linked List from a Ternary Tree 267
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
47 Data Structure design to perform required operations 274
3
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
48 Decimal Equivalent of Binary Linked List 278
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
49 Delete N nodes after M nodes of a linked list 280
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
50 Delete a Doubly Linked List node at a given position 286
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
51 Delete a Linked List node at a given position 290
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
52 Delete a given node in Linked List under given constraints 297
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
53 Delete a linked list using recursion 303
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
54 Delete a node in a Doubly Linked List 305
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
55 Delete all occurrences of a given key in a doubly linked list 314
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
56 Delete all occurrences of a given key in a linked list 319
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
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
59 Delete alternate nodes of a Linked List 331
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
60 Delete last occurrence of an item from linked list 337
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
61 Delete middle of linked list 342
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
62 Delete multiple occurrences of key in Linked list using double pointer 345
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
63 Delete nodes which have a greater value on right side 348
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
4
Contents
64 Deletion from a Circular Linked List 355
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
65 Detect and Remove Loop in a Linked List 360
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
66 Detect loop in a linked list 384
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
67 Double elements and append zeros in linked list 395
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
68 Doubly Circular Linked List | Set 1 (Introduction and Insertion) 400
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
69 Doubly Circular Linked List | Set 2 (Deletion) 409
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
70 Doubly Linked List | Set 1 (Introduction and Insertion) 416
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
71 Exchange first and last nodes in Circular Linked List 438
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
72 Extract Leaves of a Binary Tree in a Doubly Linked List 442
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
73 Find Length of a Linked List (Iterative and Recursive) 450
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
74 Find a triplet from three linked lists with sum equal to a given number 460
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
75 Find common elements in three linked lists 466
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
76 Find first node of loop in a linked list 470
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
77 Find kth node from Middle towards Head of a Linked List 475
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478
78 Find length of loop in linked list 479
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
79 Find middle of singly linked list Recursively 482
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
80 Find modular node in a linked list 485
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
5
Contents
81 Find pair for given sum in a sorted singly linked without extra space 489
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
82 Find pairs with given sum in doubly linked list 495
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
83 Find smallest and largest elements in singly linked list 499
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
84 Find the first non-repeating character from a stream of characters 503
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
85 Find the fractional (or n/k – th) node in linked list 511
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
86 Find the largest node in Doubly linked list 516
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
87 Find the middle of a given linked list in C and Java 519
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
88 Find the sum of last n nodes of the given Linked List 526
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
89 Find unique elements in linked list 538
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
90 First common element in two linked lists 541
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
91 First non-repeating in a linked list 544
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
92 Flatten a binary tree into linked list 547
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
93 Flatten a binary tree into linked list | Set-2 552
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
94 Flatten a multi-level linked list | Set 2 (Depth wise) 556
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559
95 Flatten a multilevel linked list 560
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
96 Flattening a Linked List 568
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
97 Function to check if a singly linked list is palindrome 575
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
6
Contents
98 Generic Linked List in C 589
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
99 Given a linked list of line segments, remove middle points 592
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600
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
102 Given only a pointer to a node to be deleted in a singly linked list,
how do you delete it? 616
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619
103 Given only a pointer/reference to a node to be deleted in a singly
linked list, how do you delete it? 620
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624
104 Hashtables Chaining with Doubly Linked Lists 625
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
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
107 Identical Linked Lists 636
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641
108 Implementation of Deque using doubly linked list 642
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 650
109 Implementing Iterator pattern of a single Linked List 651
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656
110 Implementing a Linked List in Java using Class 657
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679
111 In-place Merge two linked lists without changing links of first list 680
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683
112 In-place conversion of Sorted DLL to Balanced BST 684
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692
113 Insert a node after the n-th node from the end 693
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 698
114 Insert a node at a specific position in a linked list 699
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
118 Insertion Sort for Singly Linked List 722
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 727
119 Insertion at Specific Position in a Circular Doubly Linked List 728
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 733
120 Insertion in Unrolled Linked List 734
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 740
121 Intersection of two Sorted Linked Lists 741
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 748
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
124 Java Program for Reverse a linked list 759
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759
125 Josephus Circle using circular linked list 764
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 768
126 Large number arithmetic using doubly linked list 769
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785
127 Length of longest palindrome list in a linked list using O(1) extra space786
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
128 Linked List Pair Sum 790
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 794
129 Linked List Sum of Nodes Between 0s 795
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 797
130 Linked List representation of Disjoint Set Data Structures 798
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803
8
Contents
131 Linked List vs Array 804
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805
132 Linked List | Set 1 (Introduction) 806
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 816
133 Linked List | Set 2 (Inserting a node) 817
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 832
134 Linked List | Set 3 (Deleting a node) 833
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 839
135 LinkedList in Java 840
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 842
136 Longest Common Prefix using Linked List 843
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 846
137 Longest common suffix of two linked lists 847
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 850
138 Longest increasing sublist in a linked list 851
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 854
139 Lucky alive person in a circle | Code Solution to sword puzzle 855
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 857
140 Majority element in a linked list 858
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 862
141 Make a loop at k-th position in a linked list 863
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 865
142 Make middle node head in a linked list 866
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 871
143 Maximum occurring character in a linked list 872
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 875
144 Memory efficient doubly linked list 876
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 876
145 Merge K sorted linked lists | Set 1 877
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 881
146 Merge Sort for Doubly Linked List 882
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 890
147 Merge Sort for Linked Lists 891
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 898
9
Contents
148 Merge Sort for Linked Lists in JavaScript 899
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 903
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
152 Merge two sorted linked list without duplicates 923
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 926
153 Merge two sorted linked lists 927
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 934
154 Merge two sorted linked lists such that merged list is in reverse order 935
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 941
155 Merge two sorted lists (in-place) 942
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 947
156 Modify and Rearrange List 948
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 952
157 Modify contents of Linked List 953
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 960
158 Move all occurrences of an element to end in a linked list 961
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 966
159 Move all zeros to the front of the linked list 967
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 970
160 Move first element to end of a given Linked List 971
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 973
161 Move last element to front of a given Linked List 974
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 978
162 Multiply two numbers represented as linked lists into a third list 979
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 984
163 Multiply two numbers represented by Linked Lists 985
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 990
164 Multiply two polynomials 991
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 995
10
Contents
165 Pairwise swap elements of a given linked list 996
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1002
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
171 Practice questions for Linked List and Recursion 1032
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1035
172 Print Reverse a linked list using Stack 1036
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1039
173 Print alternate nodes of a linked list using recursion 1040
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1042
174 Print reverse of a Linked List without actually reversing 1043
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1046
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
177 Priority Queue using Linked List 1054
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1057
178 Priority Queue using doubly linked list 1058
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1061
179 Program for n’th node from the end of a Linked List 1062
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1070
180 Program to find size of Doubly Linked List 1071
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1073
181 Queue based approach for first non-repeating character in a stream 1074
11
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1077
182 Queue | Set 2 (Linked List Implementation) 1078
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1083
183 QuickSort on Doubly Linked List 1084
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1091
184 QuickSort on Singly Linked List 1092
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1096
185 Rearrange a Linked List in Zig-Zag fashion 1097
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1100
186 Rearrange a Linked List in Zig-Zag fashion | Set-2 1101
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1105
187 Rearrange a given linked list in-place. 1106
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1114
188 Rearrange a given list such that it consists of alternating minimum
maximum elements 1115
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1117
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
192 Recursive approach for alternating split of Linked List 1130
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1132
193 Recursive function to delete k-th node from linked list 1133
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1135
194 Recursive insertion and traversal linked list 1136
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1138
195 Recursive selection sort for singly linked list | Swapping node links 1139
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1143
196 Recursively Reversing a linked list (A simple implementation) 1144
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1146
197 Remove all occurrences of duplicates from a sorted Linked List 1147
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1153
12
Contents
198 Remove duplicates from a sorted doubly linked list 1154
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1158
199 Remove duplicates from a sorted linked list 1159
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1165
200 Remove duplicates from a sorted linked list using recursion 1166
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1168
201 Remove duplicates from an unsorted doubly linked list 1169
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1176
202 Remove duplicates from an unsorted linked list 1177
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1185
203 Remove every k-th node of the linked list 1186
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1189
204 Replace nodes with duplicates in linked list 1190
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1193
205 Reverse a Doubly Linked List 1194
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1200
206 Reverse a Doubly Linked List | Set 4 (Swapping Data) 1201
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1204
207 Reverse a Doubly Linked List | Set-2 1205
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1208
208 Reverse a Doubly linked list using recursion 1209
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1212
209 Reverse a Linked List according to its Size 1213
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1216
210 Reverse a Linked List in groups of given size | Set 1 1217
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1223
211 Reverse a Linked List in groups of given size | Set 2 1224
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1227
212 Reverse a circular linked list 1228
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1230
213 Reverse a doubly circular linked list 1231
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1235
214 Reverse a doubly linked list in groups of given size 1236
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1239
13
Contents
215 Reverse a linked list 1240
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1255
216 Reverse a stack without using extra space in O(n) 1256
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1260
217 Reverse a sublist of linked list 1261
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1264
218 Reverse alternate K nodes in a Singly Linked List 1265
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1270
219 Reverse each word in a linked list node 1271
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1273
220 Reverse first K elements of given linked list 1274
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1278
221 Reverse nodes of a linked list without affecting the special characters 1279
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1285
222 Rotate Doubly linked list by N nodes 1286
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1290
223 Rotate Linked List block wise 1291
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1294
224 Rotate a Linked List 1295
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1302
225 Search an element in a Linked List (Iterative and Recursive) 1303
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1313
226 Segregate even and odd nodes in a Linked List 1314
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1326
227 Segregate even and odd nodes in a Linked List using Deque 1327
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1330
228 Select a Random Node from a Singly Linked List 1331
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1337
229 Self Organizing List : Count Method 1338
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1343
230 Self Organizing List : Move to Front Method 1344
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1348
231 Skip List | Set 2 (Insertion) 1349
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1358
14
Contents
232 Skip List | Set 3 (Searching and Deletion) 1359
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1372
233 Sort a k sorted doubly linked list 1373
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1377
234 Sort a linked list of 0s, 1s and 2s 1378
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1385
235 Sort a linked list of 0s, 1s and 2s by changing links 1386
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1389
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
238 Sort the biotonic doubly linked list 1406
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1410
239 Sort the biotonic doubly linked list | Set-2 1411
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1415
240 Sort the linked list in the order of elements appearing in the array 1416
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1419
241 Sorted Linked List to Balanced BST 1420
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1428
242 Sorted insert for circular linked list 1429
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1436
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
245 Split a Circular Linked List into two halves 1446
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1454
246 Squareroot(n)-th node in a Linked List 1455
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1458
247 Stack Data Structure (Introduction and Program) 1459
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1470
248 Sublist Search (Search a linked list in another list) 1471
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1474
15
Contents
249 Subtract Two Numbers represented as Linked Lists 1475
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1483
250 Sudo Placement[1.4] | K Sum 1484
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1490
251 Sum of the nodes of a Singly Linked List 1491
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1495
252 Swap Kth node from beginning with Kth node from end in a Linked
List 1496
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1502
253 Swap nodes in a linked list without swapping data 1503
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1513
254 The Great Tree-List Recursion Problem. 1514
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1514
255 Union and Intersection of two Linked Lists 1515
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1527
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
258 Unrolled Linked List | Set 1 (Introduction) 1540
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1543
259 Write a function that counts the number of times a given int occurs in
a Linked List 1544
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1551
260 Write a function to delete a Linked List 1552
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1556
261 Write a function to get Nth node in a Linked List 1557
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1564
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 Programmer’s approach of looking at Array vs. Linked List - GeeksforGeeks
In general, array is considered a data structure for which size is fixed at the compile time
and array memory is allocated either from Data section (e.g. global array) or Stack section
(e.g. local array).
Similarly, linked list is considered a data structure for which size is not fixed and memory
is allocated from Heap section (e.g. using malloc() etc.) as and when needed. In this sense,
array is taken as a static data structure (residing in Data or Stack section) while linked list
is taken as a dynamic data structure (residing in Heap section). Memory representation of
array and linked list can be visualized as follows:
An array of 4 elements (integer type) which have been initialized with 1, 2, 3 and 4. Sup-
pose, these elements are allocated at memory addresses 0x100, 0x104, 0x108 and 0x10C
respectively.
[(1)] [(2)] [(3)] [(4)]
0x100 0x104 0x108 0x10C
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.
[(1), 0x308] [(2),0x404] [(3),0x20B] [(4),NULL]
0x200 0x308 0x404 0x20B
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;
/* nextNode is the pointer to next node in linked list*/
struct llNode * nextNode;
};
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*/
int * dynArr = (int *)malloc(sizeof(int)*arrSize);
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;
/*Here, note that nextIndex stores the location of next node in
linked list*/
int nextIndex;
};
struct sllNode arrayLL[5];
If we initialize this linked list (which is actually an array), it would look as follows in memory:
[(0),-1] [(0),-1] [(0),-1] [(0),-1] [(0),-1]
0x500 0x508 0x510 0x518 0x520
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
[(1),1] [(2),2] [(3),3] [(4),-2] [(0),-1]
0x500 0x508 0x510 0x518 0x520
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:
[(1),2] [(0),-1] [(3),3] [(4),-2] [(0),-1]
0x500 0x508 0x510 0x518 0x520
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
[(1),1] [(2),3] [(0),-1] [(4),4] [(5),-2]
0x500 0x508 0x510 0x518 0x520
After inserting a new node with data 8, the linked list would look as follows with head index
as 2.
[(1),1] [(2),3] [(8),0] [(4),4] [(5),-2]
0x500 0x508 0x510 0x518 0x520
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:
[(4),2] [(0),3] [(5),5] [(0),-1] [(0),1] [(9),-1]
0x500 0x508 0x510 0x518 0x520 0x528
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
Add 1 to a number represented
as linked list
Add 1 to a number represented as linked list - GeeksforGeeks
Number is represented in linked list such that each digit corresponds to a node in linked list.
Add 1 to it. For example 1999 is represented as (1-> 9-> 9 -> 9) and adding 1 to it should
change it to (2->0->0->0)
Below are the steps :
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.
Below is C++ implementation of above steps.
// C++ program to add 1 to a linked list
#include<bits/stdc++.h>
/* Linked list node */
struct Node
{
int data;
Node* next;
};
/* Function to create a new node with given data */
Node *newNode(int data)
{
Node *new_node = new Node;
new_node->data = data;
22
Chapter 2. Add 1 to a number represented as linked list
new_node->next = NULL;
return new_node;
}
/* Function to reverse the linked list */
Node *reverse(Node *head)
{
Node * prev = NULL;
Node * current = head;
Node * next;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}
/* Adds one to a linked lists and return the head
node of resultant list */
Node *addOneUtil(Node *head)
{
// res is head node of the resultant list
Node* res = head;
Node *temp, *prev = NULL;
int carry = 1, sum;
while (head != NULL) //while both lists exist
{
// Calculate value of next digit in resultant list.
// The next digit is sum of following things
// (i) Carry
// (ii) Next digit of head list (if there is a
// next digit)
sum = carry + head->data;
// update carry for next calulation
carry = (sum >= 10)? 1 : 0;
// update sum if it is greater than 10
sum = sum % 10;
// Create a new node with sum as data
head->data = sum;
23
Chapter 2. Add 1 to a number represented as linked list
// Move head and second pointers to next nodes
temp = head;
head = head->next;
}
// if some carry is still there, add a new node to
// result list.
if (carry > 0)
temp->next = newNode(carry);
// return head of the resultant list
return res;
}
// This function mainly uses addOneUtil().
Node* addOne(Node *head)
{
// Reverse linked list
head = reverse(head);
// Add one from left to right of reversed
// list
head = addOneUtil(head);
// Reverse the modified list
return reverse(head);
}
// A utility function to print a linked list
void printList(Node *node)
{
while (node != NULL)
{
printf("%d", node->data);
node = node->next;
}
printf("\n");
}
/* Driver program to test above function */
int main(void)
{
Node *head = newNode(1);
head->next = newNode(9);
head->next->next = newNode(9);
head->next->next->next = newNode(9);
printf("List is ");
24
Chapter 2. Add 1 to a number represented as linked list
printList(head);
head = addOne(head);
printf("\nResultant list is ");
printList(head);
return 0;
}
Output:
List is 1999
Resultant list is 2000
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.
// Recursive C++ program to add 1 to a linked list
#include<bits/stdc++.h>
/* Linked list node */
struct Node
{
int data;
Node* next;
};
/* Function to create a new node with given data */
Node *newNode(int data)
{
Node *new_node = new Node;
new_node->data = data;
new_node->next = NULL;
return new_node;
}
// Recursively add 1 from end to beginning and returns
// carry after all nodes are processed.
int addWithCarry(Node *head)
{
// If linked list is empty, then
25
Chapter 2. Add 1 to a number represented as linked list
// return carry
if (head == NULL)
return 1;
// Add carry returned be next node call
int res = head->data + addWithCarry(head->next);
// Update data and return new carry
head->data = (res) % 10;
return (res) / 10;
}
// This function mainly uses addWithCarry().
Node* addOne(Node *head)
{
// Add 1 to linked list from end to beginning
int carry = addWithCarry(head);
// If there is carry after processing all nodes,
// then we need to add a new node to linked list
if (carry)
{
Node *newNode = new Node;
newNode->data = carry;
newNode->next = head;
return newNode; // New node becomes head now
}
return head;
}
// A utility function to print a linked list
void printList(Node *node)
{
while (node != NULL)
{
printf("%d", node->data);
node = node->next;
}
printf("\n");
}
/* Driver program to test above function */
int main(void)
{
Node *head = newNode(1);
head->next = newNode(9);
head->next->next = newNode(9);
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);
printf("\nResultant list is ");
printList(head);
return 0;
}
Output:
List is 1999
Resultant list is 2000
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
Add two numbers represented
by linked lists | Set 1
Add two numbers represented by linked lists | Set 1 - GeeksforGeeks
Given two numbers represented by two lists, write a function that returns sum list. The
sum list is list representation of addition of two input numbers.
Example 1
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>
/* Linked list node */
struct Node
{
int data;
struct Node* next;
};
/* Function to create a new node with given data */
struct Node *newNode(int data)
{
struct Node *new_node = (struct Node *) malloc(sizeof(struct Node));
new_node->data = data;
new_node->next = NULL;
return new_node;
}
/* 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 = newNode(new_data);
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* 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;
while (first != NULL || second != NULL) //while both lists exist
{
// Calculate value of next digit in resultant list.
// The next digit is sum of following things
// (i) Carry
// (ii) Next digit of first list (if there is a next digit)
// (ii) Next digit of second list (if there is a next digit)
sum = carry + (first? first->data: 0) + (second? second->data: 0);
29
Chapter 3. Add two numbers represented by linked lists | Set 1
// update carry for next calulation
carry = (sum >= 10)? 1 : 0;
// update sum if it is greater than 10
sum = sum % 10;
// Create a new node with sum as data
temp = newNode(sum);
// 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;
// Set prev for next insertion
prev = temp;
// Move first and second pointers to next nodes
if (first) first = first->next;
if (second) second = second->next;
}
if (carry > 0)
temp->next = newNode(carry);
// return head of the resultant list
return res;
}
// A utility function to print a linked list
void printList(struct Node *node)
{
while(node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
/* Driver program to test above function */
int main(void)
{
struct Node* res = NULL;
struct Node* first = NULL;
struct Node* second = NULL;
30
Chapter 3. Add two numbers represented by linked lists | Set 1
// create first list 7->5->9->4->6
push(&first, 6);
push(&first, 4);
push(&first, 9);
push(&first, 5);
push(&first, 7);
printf("First List is ");
printList(first);
// create second list 8->4
push(&second, 4);
push(&second, 8);
printf("Second List is ");
printList(second);
// Add the two lists and see result
res = addTwoLists(first, second);
printf("Resultant list is ");
printList(res);
return 0;
}
Java
// Java program to add two numbers represented by linked list
class LinkedList {
static Node head1, head2;
static class Node {
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
while (first != null || second != null) //while both lists exist
{
// Calculate value of next digit in resultant list.
// The next digit is sum of following things
// (i) Carry
// (ii) Next digit of first list (if there is a next digit)
// (ii) Next digit of second list (if there is a next digit)
sum = carry + (first != null ? first.data : 0)
+ (second != null ? second.data : 0);
// update carry for next calulation
carry = (sum >= 10) ? 1 : 0;
// update sum if it is greater than 10
sum = sum % 10;
// Create a new node with sum as data
temp = new Node(sum);
// 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;
}
// Set prev for next insertion
prev = temp;
// Move first and second pointers to next nodes
if (first != null) {
first = first.next;
}
if (second != null) {
second = second.next;
}
}
if (carry > 0) {
temp.next = new Node(carry);
}
// return head of the resultant list
return res;
}
32
Chapter 3. Add two numbers represented by linked lists | Set 1
/* Utility function to print a linked list */
void printList(Node head) {
while (head != null) {
System.out.print(head.data + " ");
head = head.next;
}
System.out.println("");
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
// creating first list
list.head1 = new Node(7);
list.head1.next = new Node(5);
list.head1.next.next = new Node(9);
list.head1.next.next.next = new Node(4);
list.head1.next.next.next.next = new Node(6);
System.out.print("First List is ");
list.printList(head1);
// creating seconnd list
list.head2 = new Node(8);
list.head2.next = new Node(4);
System.out.print("Second List is ");
list.printList(head2);
// add the two lists and see the result
Node rs = list.addTwoLists(head1, head2);
System.out.print("Resultant List is ");
list.printList(rs);
}
}
// this code has been contributed by Mayank Jaiswal
Python
# Python program to add two numbers represented by linked list
# Node class
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
33
Chapter 3. Add two numbers represented by linked lists | Set 1
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Add contents of two linked lists and return the head
# node of resultant list
def addTwoLists(self, first, second):
prev = None
temp = None
carry = 0
# While both list exists
while(first is not None or second is not None):
# Calculate the value of next digit in
# resultant list
# The next digit is sum of following things
# (i) Carry
# (ii) Next digit of first list (if ther is a
# next digit)
# (iii) Next digit of second list ( if there
# is a next digit)
fdata = 0 if first is None else first.data
sdata = 0 if second is None else second.data
Sum = carry + fdata + sdata
# update carry for next calculation
carry = 1 if Sum >= 10 else 0
# update sum if it is greater than 10
Sum = Sum if Sum < 10 else Sum % 10
# Create a new node with sum as data
temp = Node(Sum)
# if this is the first node then set it as head
# of resultant list
if self.head is None:
self.head = temp
34
Chapter 3. Add two numbers represented by linked lists | Set 1
else :
prev.next = temp
# Set prev for next insertion
prev = temp
# Move first and second pointers to next nodes
if first is not None:
first = first.next
if second is not None:
second = second.next
if carry > 0:
temp.next = Node(carry)
# Utility function to print the linked LinkedList
def printList(self):
temp = self.head
while(temp):
print temp.data,
temp = temp.next
# Driver program to test above function
first = LinkedList()
second = LinkedList()
# Create first list
first.push(6)
first.push(4)
first.push(9)
first.push(5)
first.push(7)
print "First List is ",
first.printList()
# Create second list
second.push(4)
second.push(8)
print "\nSecond List is ",
second.printList()
# Add the two lists and see result
res = LinkedList()
res.addTwoLists(first.head, second.head)
print "\nResultant list is ",
res.printList()
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
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
Add two numbers represented
by linked lists | Set 2
Add two numbers represented by linked lists | Set 2 - GeeksforGeeks
Given two numbers represented by two linked lists, write a function that returns sum list.
The sum list is linked list representation of addition of two input numbers. It is not allowed
to modify the lists. Also, not allowed to use explicit extra space (Hint: Use Recursion).
Example
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
// A recursive program to add two linked lists
#include <stdio.h>
#include <stdlib.h>
// A linked List Node
struct Node
{
int data;
struct Node* next;
};
typedef struct Node node;
/* A utility function to insert a node at the beginning of linked list */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* A utility function to print linked list */
void printList(struct Node *node)
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
printf("n");
}
// A utility function to swap two pointers
38
Chapter 4. Add two numbers represented by linked lists | Set 2
void swapPointer( Node** a, Node** b )
{
node* t = *a;
*a = *b;
*b = t;
}
/* A utility function to get size of linked list */
int getSize(struct Node *node)
{
int size = 0;
while (node != NULL)
{
node = node->next;
size++;
}
return size;
}
// 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;
// Allocate memory for sum node of current two nodes
Node* result = (Node *)malloc(sizeof(Node));
// Recursively add remaining nodes and get the carry
result->next = addSameSize(head1->next, head2->next, carry);
// add digits of current nodes and propagated carry
sum = head1->data + head2->data + *carry;
*carry = sum / 10;
sum = sum % 10;
// Assigne the sum to current node of resultant list
result->data = 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;
// If diff. number of nodes are not traversed, add carry
if (head1 != cur)
{
addCarryToRemaining(head1->next, cur, carry, result);
sum = head1->data + *carry;
*carry = sum/10;
sum %= 10;
// add this node to the front of the result
push(result, 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;
// first list is empty
if (head1 == NULL)
{
*result = head2;
return;
}
// second list is empty
else if (head2 == NULL)
{
*result = head1;
return;
}
int size1 = getSize(head1);
int size2 = getSize(head2) ;
int carry = 0;
// Add same size lists
if (size1 == size2)
40
Chapter 4. Add two numbers represented by linked lists | Set 2
*result = addSameSize(head1, head2, &carry);
else
{
int diff = abs(size1 - size2);
// First list should always be larger than second list.
// If not, swap pointers
if (size1 < size2)
swapPointer(&head1, &head2);
// move diff. number of nodes in first list
for (cur = head1; diff--; cur = cur->next);
// get addition of same size lists
*result = addSameSize(cur, head2, &carry);
// get addition of remaining first list and carry
addCarryToRemaining(head1, cur, &carry, result);
}
// if some carry is still there, add a new node to the fron of
// the result list. e.g. 999 and 87
if (carry)
push(result, carry);
}
// Driver program to test above functions
int main()
{
Node *head1 = NULL, *head2 = NULL, *result = NULL;
int arr1[] = {9, 9, 9};
int arr2[] = {1, 8};
int size1 = sizeof(arr1) / sizeof(arr1[0]);
int size2 = sizeof(arr2) / sizeof(arr2[0]);
// Create first list as 9->9->9
int i;
for (i = size1-1; i >= 0; --i)
push(&head1, arr1[i]);
// Create second list as 1->8
for (i = size2-1; i >= 0; --i)
push(&head2, arr2[i]);
addList(head1, head2, &result);
41
Chapter 4. Add two numbers represented by linked lists | Set 2
printList(result);
return 0;
}
Java
// Java program to add two linked lists
public class linkedlistATN
{
class node
{
int val;
node next;
public node(int val)
{
this.val = val;
}
}
// Function to print linked list
void printlist(node head)
{
while (head != null)
{
System.out.print(head.val + " ");
head = head.next;
}
}
node head1, head2, result;
int carry;
/* A utility function to push a value to linked list */
void push(int val, int list)
{
node newnode = new node(val);
if (list == 1)
{
newnode.next = head1;
head1 = newnode;
}
else if (list == 2)
{
newnode.next = head2;
42
Chapter 4. Add two numbers represented by linked lists | Set 2
head2 = newnode;
}
else
{
newnode.next = result;
result = newnode;
}
// 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
void addsamesize(node n, node m)
{
// Since the function assumes linked lists are of
// same size, check any of the two head pointers
if (n == null)
return;
// Recursively add remaining nodes and get the carry
addsamesize(n.next, m.next);
// add digits of current nodes and propagated carry
int sum = n.val + m.val + carry;
carry = sum / 10;
sum = sum % 10;
// Push this to result list
push(sum, 3);
node cur;
// 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 to the left side of larger list to get the
// final result.
void propogatecarry(node head1)
{
// If diff. number of nodes are not traversed, add carry
if (head1 != cur)
{
propogatecarry(head1.next);
int sum = carry + head1.val;
43
Chapter 4. Add two numbers represented by linked lists | Set 2
carry = sum / 10;
sum %= 10;
// add this node to the front of the result
push(sum, 3);
}
}
int getsize(node head)
{
int count = 0;
while (head != null)
{
count++;
head = head.next;
}
return count;
}
// 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 addlists()
{
// first list is empty
if (head1 == null)
{
result = head2;
return;
}
// first list is empty
if (head2 == null)
{
result = head1;
return;
}
int size1 = getsize(head1);
int size2 = getsize(head2);
// Add same size lists
if (size1 == size2)
{
addsamesize(head1, head2);
}
else
{
44
Chapter 4. Add two numbers represented by linked lists | Set 2
// First list should always be larger than second list.
// If not, swap pointers
if (size1 < size2)
{
node temp = head1;
head1 = head2;
head2 = temp;
}
int diff = Math.abs(size1 - size2);
// move diff. number of nodes in first list
node temp = head1;
while (diff-- >= 0)
{
cur = temp;
temp = temp.next;
}
// get addition of same size lists
addsamesize(cur, head2);
// get addition of remaining first list and carry
propogatecarry(head1);
}
// if some carry is still there, add a new node to
// the front of the result list. e.g. 999 and 87
if (carry > 0)
push(carry, 3);
// Driver program to test above functions
public static void main(String args[])
{
linkedlistATN list = new linkedlistATN();
list.head1 = null;
list.head2 = null;
list.result = null;
list.carry = 0;
int arr1[] = { 9, 9, 9 };
int arr2[] = { 1, 8 };
// Create first list as 9->9->9
for (int i = arr1.length - 1; i >= 0; --i)
list.push(arr1[i], 1);
// Create second list as 1->8
for (int i = arr2.length - 1; i >= 0; --i)
45
Chapter 4. Add two numbers represented by linked lists | Set 2
list.push(arr2[i], 2);
list.addlists();
list.printlist(list.result);
}
}
// This code is contributed by Rishabh Mahrsee
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
Adding two polynomials using
Linked List
Adding two polynomials using Linked List - GeeksforGeeks
Given two polynomial numbers represented by a linked list. Write a function that add these
lists means add the coefficients who have same variable powers.
Example:
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
// C++ program for addition of two polynomials
// using Linked Lists
#include<bits/stdc++.h>
using namespace std;
// Node structure containing power and coefficient of variable
struct Node
{
int coeff;
int pow;
struct Node *next;
};
// Function to create new node
void create_node(int x, int y, struct Node **temp)
{
struct Node *r, *z;
z = *temp;
if(z == NULL)
{
r =(struct Node*)malloc(sizeof(struct Node));
r->coeff = x;
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;
}
}
// Function Adding two polynomial numbers
void polyadd(struct Node *poly1, struct Node *poly2, struct Node *poly)
{
while(poly1->next && poly2->next)
{
// If power of 1st polynomial is greater then 2nd, then store 1st as it is
// and move its pointer
if(poly1->pow > poly2->pow)
{
poly->pow = poly1->pow;
poly->coeff = poly1->coeff;
poly1 = poly1->next;
}
// If power of 2nd polynomial is greater then 1st, then store 2nd as it is
// and move its pointer
else if(poly1->pow < poly2->pow)
{
poly->pow = poly2->pow;
poly->coeff = poly2->coeff;
poly2 = poly2->next;
}
// If power of both polynomial numbers is same then add their coefficients
else
{
poly->pow = poly1->pow;
poly->coeff = poly1->coeff+poly2->coeff;
poly1 = poly1->next;
poly2 = poly2->next;
}
49
Chapter 5. Adding two polynomials using Linked List
// Dynamically create new node
poly->next = (struct Node *)malloc(sizeof(struct Node));
poly = poly->next;
poly->next = NULL;
}
while(poly1->next || poly2->next)
{
if(poly1->next)
{
poly->pow = poly1->pow;
poly->coeff = poly1->coeff;
poly1 = poly1->next;
}
if(poly2->next)
{
poly->pow = poly2->pow;
poly->coeff = poly2->coeff;
poly2 = poly2->next;
}
poly->next = (struct Node *)malloc(sizeof(struct Node));
poly = poly->next;
poly->next = NULL;
}
}
// Display Linked list
void show(struct Node *node)
{
while(node->next != NULL)
{
printf("%dx^%d", node->coeff, node->pow);
node = node->next;
if(node->next != NULL)
printf(" + ");
}
}
// Driver program
int main()
{
struct Node *poly1 = NULL, *poly2 = NULL, *poly = NULL;
// Create first list of 5x^2 + 4x^1 + 2x^0
create_node(5,2,&poly1);
create_node(4,1,&poly1);
create_node(2,0,&poly1);
// Create second list of 5x^1 + 5x^0
50
Chapter 5. Adding two polynomials using Linked List
create_node(5,1,&poly2);
create_node(5,0,&poly2);
printf("1st Number: ");
show(poly1);
printf("\n2nd Number: ");
show(poly2);
poly = (struct Node *)malloc(sizeof(struct Node));
// Function add two polynomial numbers
polyadd(poly1, poly2, poly);
// Display resultant List
printf("\nAdded polynomial: ");
show(poly);
return 0;
}
Output:
1st Number: 5x^2 + 4x^1 + 2x^0
2nd Number: 5x^1 + 5x^0
Added polynomial: 5x^2 + 9x^1 + 7x^0
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
Alternate Odd and Even Nodes
in a Singly Linked List
Alternate Odd and Even Nodes in a Singly Linked List - GeeksforGeeks
Given a singly linked list, rearrange the list so that even and odd nodes are alternate in the
list.
There are two possible forms of this rearrangement. If the first data is odd, then the second
node must be even. The third node must be odd and so on. Notice that another arrangement
is possible where the first node is even, second odd, third even and so on.
Examples:
Input : 11 -> 20 -> 40 -> 55 -> 77 -> 80 -> NULL
Output : 11 -> 20 -> 55 -> 40 -> 77 -> 80 -> NULL
20, 40, 80 occur in even positions and 11, 55, 77
occur in odd positions.
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++
// CPP program to rearrange nodes
// as alternate odd even nodes in
// a Singly Linked List
#include <bits/stdc++.h>
using namespace std;
// Structure node
struct Node {
int data;
struct Node* next;
};
// A utility function to print
// linked list
void printList(struct Node* node)
{
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
cout << endl;
}
// Function to create newNode
// in a linkedlist
Node* newNode(int key)
{
Node* temp = new Node;
temp->data = key;
temp->next = NULL;
return temp;
}
// Function to insert at beginning
53
Chapter 6. Alternate Odd and Even Nodes in a Singly Linked List
Node* insertBeg(Node* head, int val)
{
Node* temp = newNode(val);
temp->next = head;
head = temp;
return head;
}
// Function to rearrange the
// odd and even nodes
void rearrangeOddEven(Node* head)
{
stack<Node*> odd;
stack<Node*> even;
int i = 1;
while (head != nullptr) {
if (head->data % 2 != 0 && i % 2 == 0) {
// Odd Value in Even Position
// Add pointer to current node
// in odd stack
odd.push(head);
}
else if (head->data % 2 == 0 && i % 2 != 0) {
// Even Value in Odd Postion
// Add pointer to current node
// in even stack
even.push(head);
}
head = head->next;
i++;
}
while (!odd.empty() && !even.empty()) {
// Swap Data at the top of two stacks
swap(odd.top()->data, even.top()->data);
odd.pop();
even.pop();
}
}
// 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);
cout << "Linked List:" << endl;
printList(head);
rearrangeOddEven(head);
cout << "Linked List after "
<< "Rearranging:" << endl;
printList(head);
return 0;
}
Output:
Linked List:
1 2 3 5 6 7 8
Linked List after Rearranging:
1 2 3 6 5 8 7
Time Complexity : O(n)
Auxiliary Space : O(n)
Method 2 (Efficient)
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
Step 3: Set PREV_TEMP to 1st element of List
Step 4: Traverse using node TEMP as long as an even
node is not encountered.
PREV_TEMP = TEMP, TEMP = TEMP->NEXT
[END OF TRAVERSAL]
Step 5: Set EVEN to TEMP. Set PREV_TEMP->NEXT to NULL
Step 6: I = HEAD, J = EVEN
Step 7: Repeat while I != NULL and J != NULL
Store next nodes of I and J in K and L
K = I->NEXT, L = J->NEXT
I->NEXT = J, J->NEXT = K, PTR = J
I = K and J = L
[END OF LOOP]
Step 8: if I == NULL
PTR->NEXT = J
[END of IF]
Step 8: Return HEAD.
Step 9: End
C++
// Cpp program to rearrange nodes
// as alternate odd even nodes in
// a Singly Linked List
#include <iostream>
#include <stack>
using namespace std;
// Structure node
struct Node {
int data;
struct Node* next;
};
// A utility function to print
// linked list
void printList(struct Node* node)
{
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
cout << endl;
}
// Function to create newNode
// in a linkedlist
Node* newNode(int key)
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;
}
// Function to insert at beginning
Node* insertBeg(Node* head, int val)
{
Node* temp = newNode(val);
temp->next = head;
head = temp;
return head;
}
// Function to rearrange the
// odd and even nodes
void rearrange(Node** head)
{
// Step 1: Segregate even and odd nodes
// Step 2: Split odd and even lists
// Step 3: Merge even list into odd list
Node* even;
Node *temp, *prev_temp;
Node *i, *j, *k, *l, *ptr;
// Step 1: Segregate Odd and Even Nodes
temp = (*head)->next;
prev_temp = *head;
while (temp != nullptr) {
// Backup next pointer of temp
Node* x = temp->next;
// If temp is odd move the node
// to beginning of list
if (temp->data % 2 != 0) {
prev_temp->next = x;
temp->next = (*head);
(*head) = temp;
}
else {
prev_temp = temp;
}
// Advance Temp Pointer
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);
while (temp != nullptr && temp->data % 2 != 0) {
prev_temp = temp;
temp = temp->next;
}
even = temp;
// End the odd List (Make last node null)
prev_temp->next = nullptr;
// Step 3:
// Merge Even List into odd
i = *head;
j = even;
while (j != nullptr && i != nullptr) {
// While both lists are not
// exhausted Backup next
// pointers of i and j
k = i->next;
l = j->next;
i->next = j;
j->next = k;
// ptr points to the latest node added
ptr = j;
// Advance i and j pointers
i = k;
j = l;
}
if (i == nullptr) {
// Odd list exhausts before even,
// append remainder of even list to odd.
ptr->next = j;
}
58
Chapter 6. Alternate Odd and Even Nodes in a Singly Linked List
// The case where even list exhausts before
// odd list is automatically handled since we
// merge the even list into the odd 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);
cout << "Linked List:" << endl;
printList(head);
cout << "Rearranged List" << endl;
rearrange(&head);
printList(head);
}
Output:
Linked List:
10 2 1 5 3 6 7 8
Rearranged List
7 10 3 2 5 6 1 8
Time Complexity : O(n)
Auxiliary Space : O(1)
Source
https://www.geeksforgeeks.org/alternate-odd-even-nodes-singly-linked-list/
59
Chapter 7
Alternate sorting of Linked list
Alternate sorting of Linked list - GeeksforGeeks
Given a linked list containing n nodes. The problem is to rearrange the nodes of the list
in such a way that the data in first node is first minimum, second node is first maximum,
third node is second minimum, fourth node is second maximum and so on.
Examples:
Input : list: 4->1->3->5->2
Output : 1->5->2->4->3
Input : list: 10->9->8->7->6->5
Output : 5->10->6->9->7->8
Approach: Following are the steps:
1. Sort the linked list using Merge Sort technique.
2. Split the list into front and back lists. Refer FrontBackProcedure of this post.
3. Now, reverse the back list. Refer this post.
4. Finally, merge the nodes of first and back lists in alternate order.
// C++ implementation of alternative sorting
// of the Linked list
#include <bits/stdc++.h>
using namespace std;
// node of a linked list
struct Node {
int data;
struct Node* next;
60
Chapter 7. Alternate sorting of Linked list
};
// function to get a new node
Node* getNode(int data)
{
// allocate space for node
Node* newNode = (Node*)malloc(sizeof(Node));
// put in the data
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 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(Node* source,
Node** frontRef, Node** backRef)
{
Node* fast;
Node* slow;
if (source == NULL || source->next == NULL) {
// length < 2 cases
*frontRef = source;
*backRef = NULL;
}
else {
slow = source;
fast = source->next;
// Advance 'fast' two nodes, and
// advance 'slow' one node
while (fast != NULL) {
fast = fast->next;
if (fast != NULL) {
slow = slow->next;
fast = fast->next;
}
}
// 'slow' is before the midpoint in the list,
// so split it in two at that point.
*frontRef = source;
*backRef = slow->next;
61
Chapter 7. Alternate sorting of Linked list
slow->next = NULL;
}
}
// function to merge two sorted lists in
// sorted order
Node* SortedMerge(Node* a, Node* b)
{
Node* result = NULL;
// Base cases
if (a == NULL)
return b;
else if (b == NULL)
return a;
// Pick either a or b, and recur
if (a->data <= b->data) {
result = a;
result->next = SortedMerge(a->next, b);
}
else {
result = b;
result->next = SortedMerge(a, b->next);
}
return result;
}
// sorts the linked list by changing
// next pointers (not data)
void MergeSort(Node** headRef)
{
Node* head = *headRef;
Node *a, *b;
// Base case -- length 0 or 1
if ((head == NULL) || (head->next == NULL))
return;
// Split head into 'a' and 'b' sublists
FrontBackSplit(head, &a, &b);
// Recursively sort the sublists
MergeSort(&a);
MergeSort(&b);
// merge the two sorted lists together
62
Chapter 7. Alternate sorting of Linked list
*headRef = SortedMerge(a, b);
}
// function to reverse the linked list
static void reverse(Node** head_ref)
{
Node* prev = NULL;
Node* current = *head_ref;
Node* next;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}
// function to alternately merge two lists
void alternateMerge(Node* head1, Node* head2)
{
Node *p, *q;
while (head1 != NULL && head2 != NULL) {
// merging nodes alternately by
// making the desired links
p = head1->next;
head1->next = head2;
head1 = p;
q = head2->next;
head2->next = head1;
head2 = q;
}
}
// function for alternative sort of the
// linked list
Node* altSortForLinkedList(Node* head)
{
// sort the linked list
MergeSort(&head);
Node *front, *back;
// Split head into 'front' and 'back' sublists
FrontBackSplit(head, &front, &back);
63
Chapter 7. Alternate sorting of Linked list
// reversing the 'back' list
reverse(&back);
// merging the nodes of 'front' and 'back'
// lists alternately
alternateMerge(front, back);
// required head of final list
return front;
}
// Function to print nodes in
// a given linked list
void printList(Node* head)
{
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
// Driver program to test above
int main()
{
// linked list: 10->9->8->7->6->5
Node* head = getNode(10);
head->next = getNode(9);
head->next->next = getNode(8);
head->next->next->next = getNode(7);
head->next->next->next->next = getNode(6);
head->next->next->next->next->next = getNode(5);
cout << "Original list: ";
printList(head);
head = altSortForLinkedList(head);
cout << "\nModified list: ";
printList(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
Time Complexity: O(n*logn).
Source
https://www.geeksforgeeks.org/alternate-sorting-linked-list/
65
Chapter 8
Alternating split of a given
Singly Linked List | Set 1
Alternating split of a given Singly Linked List | Set 1 - GeeksforGeeks
Write a function AlternatingSplit() that takes one list and divides up its nodes to make
two smaller lists ‘a’ and ‘b’. The sublists should be made from alternating elements in the
original list. So if the original list is 0->1->0->1->0->1 then one sublist should be 0->0->0
and the other should be 1->1->1.
Method 1(Simple)
The simplest approach iterates over the source list and pull nodes off the source and alter-
nately put them at the front (or beginning) of ‘a’ and b’. The only strange part is that the
nodes will be in the reverse order that they occurred in the source list. Method 2 inserts
the node at the end by keeping track of last node in sublists.
/*Program to alternatively split a linked list into two halves */
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
/* Link list node */
struct Node
{
int data;
struct Node* next;
};
/* 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;
struct Node* current = source;
while (current != NULL)
{
MoveNode(&a, ¤t); /* Move a node to list 'a' */
if (current != NULL)
{
MoveNode(&b, ¤t); /* Move a node to list 'b' */
}
}
*aRef = a;
*bRef = b;
}
/* 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.
Before calling MoveNode():
source == {1, 2, 3}
dest == {1, 2, 3}
Affter calling MoveNode():
source == {2, 3}
dest == {1, 1, 2, 3}
*/
void MoveNode(struct Node** destRef, struct Node** sourceRef)
{
/* the front source node */
struct Node* newNode = *sourceRef;
assert(newNode != NULL);
/* Advance the source pointer */
*sourceRef = newNode->next;
/* Link the old dest off the new node */
newNode->next = *destRef;
/* Move dest to point to the new node */
*destRef = newNode;
}
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));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print nodes in a given linked list */
void printList(struct Node *node)
{
while(node!=NULL)
{
printf("%d ", node->data);
node = node->next;
}
}
/* Drier program to test above functions*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
struct Node* a = NULL;
struct Node* b = NULL;
/* Let us create a sorted linked list to test the functions
Created linked list will be 0->1->2->3->4->5 */
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
push(&head, 0);
printf("\n Original linked List: ");
printList(head);
68
Chapter 8. Alternating split of a given Singly Linked List | Set 1
/* Remove duplicates from linked list */
AlternatingSplit(head, &a, &b);
printf("\n Resultant Linked List 'a' ");
printList(a);
printf("\n Resultant Linked List 'b' ");
printList(b);
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.
void AlternatingSplit(struct Node* source, struct Node** aRef,
struct Node** bRef)
{
struct Node aDummy;
struct Node* aTail = &aDummy; /* points to the last node in 'a' */
struct Node bDummy;
struct Node* bTail = &bDummy; /* points to the last node in 'b' */
struct Node* current = source;
aDummy.next = NULL;
bDummy.next = NULL;
while (current != NULL)
{
MoveNode(&(aTail->next), ¤t); /* add at 'a' tail */
aTail = aTail->next; /* advance the 'a' tail */
if (current != NULL)
{
MoveNode(&(bTail->next), ¤t);
bTail = bTail->next;
}
}
*aRef = aDummy.next;
*bRef = bDummy.next;
}
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
An interesting method to print
reverse of a linked list
An interesting method to print reverse of a linked list - GeeksforGeeks
We are given a linked list, we need to print the linked list in reverse order.
Examples:
Input : list : 5-> 15-> 20-> 25
Output : Reversed Linked list : 25-> 20-> 15-> 5
Input : list : 85-> 15-> 4-> 20
Output : Reversed Linked list : 20-> 4-> 15-> 85
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.
// C program to print reverse of list
71
Chapter 9. An interesting method to print reverse of a linked list
#include <stdio.h>
#include <stdlib.h>
/* Link list node */
struct Node {
int data;
struct Node* next;
};
/* Function to reverse the linked list */
void printReverse(struct Node** head_ref, int n)
{
int j = 0;
struct Node* current = *head_ref;
while (current != NULL) {
// For each node, print proper number
// of spaces before printing it
for (int i = 0; i < 2 * (n - j); i++)
printf(" ");
// use of carriage return to move back
// and print.
printf("%dr", current->data);
current = current->next;
j++;
}
}
/* Function to push a node */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
/* Function to print linked list and find its
length */
int printList(struct Node* head)
{
// i for finding length of list
int i = 0;
struct Node* temp = head;
72
Chapter 9. An interesting method to print reverse of a linked list
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
i++;
}
return i;
}
/* Driver program to test above function*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
// list nodes are as 6 5 4 3 2 1
push(&head, 1);
push(&head, 2);
push(&head, 3);
push(&head, 4);
push(&head, 5);
push(&head, 6);
printf("Given linked list:n");
// printlist print the list and
// return the size of list
int n = printList(head);
// print reverse list with help
// of carriage return function
printf("nReversed Linked list:n");
printReverse(&head, n);
return 0;
}
Output:
Given linked list:
6 5 4 3 2 1
Reversed Linked List:
1 2 3 4 5 6
Input and Output Illustration :
Input : 6 5 4 3 2 1
1st Iteration _ _ _ _ _ 6
2nd Iteration _ _ _ _ 5 6
3rd Iteration _ _ _ 4 5 6
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
Applications of linked list data
structure
Applications of linked list data structure - GeeksforGeeks
A linked list is a linear data structure, in which the elements are not stored at contiguous
memory locations. The elements in a linked list are linked using pointers as shown in the
below image:
Applications of linked list in computer science –
1. Implementation of stacks and queues
2. Implementation of graphs : Adjacency list representation of graphs is most popular
which is uses linked list to store adjacent vertices.
3. Dynamic memory allocation : We use linked list of free blocks.
4. Maintaining directory of names
5. Performing arithmetic operations on long integers
6. Manipulation of polynomials by storing constants in the node of linked list
7. representing sparse matrices
Applications of linked list in real world-
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.
Applications of Circular Linked Lists:
1. Useful for implementation of queue. Unlike thisimplementation, we don’t need to
maintain two pointers for front and rear if we use circular linked list. We can maintain
a pointer to the last inserted node and front can always be obtained as next of last.
2. Circular lists are useful in applications to repeatedly go around the list. For example,
when multiple applications are running on a PC, it is common for the operating system
to put the running applications on a list and then to cycle through them, giving each
of them a slice of time to execute, and then making them wait while the CPU is given
to another application. It is convenient for the operating system to use a circular list
so that when it reaches the end of the list it can cycle around to the front of the list.
3. Circular Doubly Linked Lists are used for implementation of advanced data structures
like Fibonacci Heap.
An example problem:
Design a data structure that supports following operations efficiently.
1. getMin : Gets minimum
2. extractMin : Removes minimum
3. getMax : Gets maximum
4. extractMax : Removes maximum
5. insert : Inserts an item. It may be assumed that the inserted item is always greater
than maximum so far. For example, a valid insertion order is 10, 12, 13, 20, 50.
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
Arrange consonants and vowels
nodes in a linked list
Arrange consonants and vowels nodes in a linked list - GeeksforGeeks
Given a singly linked list, we need to arrange the consonants and vowel nodes of it in such
a way that all the vowels nodes come before the consonants while maintaining the order of
their arrival.
Examples:
Input : a -> b -> c -> e -> d ->
o -> x -> i
Output : a -> e -> o -> i -> b ->
c -> d -> x
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:
a -> b -> c -> e -> d -> o -> x -> i
say our latestVowel reference references the ‘a’ node, and that we currently reached the ‘e’
node. We do:
a -> e -> b -> c -> d -> o -> x -> i
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.
/* C++ program to arrange consonants and
vowels nodes in a linked list */
#include<bits/stdc++.h>
using namespace std;
/* A linked list node */
struct Node
{
char data;
struct Node *next;
};
/* Function to add new node to the List */
Node *newNode(char key)
{
Node *temp = new Node;
temp->data = key;
temp->next = NULL;
return temp;
}
// utility function to print linked list
void printlist(Node *head)
{
if (! head)
{
cout << "Empty List\n";
return;
}
while (head != NULL)
{
cout << head->data << " ";
if (head->next)
cout << "-> ";
head = head->next;
}
cout << endl;
}
// utility function for checking vowel
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');
}
/* function to arrange consonants and
vowels nodes */
Node *arrange(Node *head)
{
Node *newHead = head;
// for keep track of vowel
Node *latestVowel;
Node *curr = head;
// list is empty
if (head == NULL)
return NULL;
// We need to discover the first vowel
// in the list. It is going to be the
// returned head, and also the initial
// latestVowel.
if (isVowel(head->data))
// first element is a vowel. It will
// also be the new head and the initial
// latestVowel;
latestVowel = head;
else
{
// First element is not a vowel. Iterate
// through the list until we find a vowel.
// Note that curr points to the element
// *before* the element with the vowel.
while (curr->next != NULL &&
!isVowel(curr->next->data))
curr = curr->next;
// This is an edge case where there are
// only consonants in the list.
if (curr->next == NULL)
return head;
79
Chapter 11. Arrange consonants and vowels nodes in a linked list
// Set the initial latestVowel and the
// new head to the vowel item that we found.
// Relink the chain of consonants after
// that vowel item:
// old_head_consonant->consonant1->consonant2->
// vowel->rest_of_list becomes
// vowel->old_head_consonant->consonant1->
// consonant2->rest_of_list
latestVowel = newHead = curr->next;
curr->next = curr->next->next;
latestVowel->next = head;
}
// Now traverse the list. Curr is always the item
// *before* the one we are checking, so that we
// can use it to re-link.
while (curr != NULL && curr->next != NULL)
{
if (isVowel(curr->next->data))
{
// The next discovered item is a vowel
if (curr == latestVowel)
{
// If it comes directly after the
// previous vowel, we don't need to
// move items around, just mark the
// new latestVowel and advance curr.
latestVowel = curr = curr->next;
}
else
{
// But if it comes after an intervening
// chain of consonants, we need to chain
// the newly discovered vowel right after
// the old vowel. Curr is not changed as
// after the re-linking it will have a
// new next, that has not been checked yet,
// and we always keep curr at one before
// the next to check.
Node *temp = latestVowel->next;
// Chain in new vowel
latestVowel->next = curr->next;
// Advance latestVowel
latestVowel = latestVowel->next;
80
Chapter 11. Arrange consonants and vowels nodes in a linked list
// Remove found vowel from previous place
curr->next = curr->next->next;
// Re-link chain of consonants after latestVowel
latestVowel->next = temp;
}
}
else
{
// No vowel in the next element, advance curr.
curr = curr->next;
}
}
return newHead;
}
// 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');
printf("Linked list before :\n");
printlist(head);
head = arrange(head);
printf("Linked list after :\n");
printlist(head);
return 0;
}
Output:
Linked list before :
a -> b -> c -> e -> d -> o -> x -> i
Linked list after :
a -> e -> o -> i -> b -> c -> d -> x
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
Binary Search on Singly Linked
List
Binary Search on Singly Linked List - GeeksforGeeks
Given a singly linked list and a key, find key using binary search approach.
To perform a Binary search based on Divide and Conquer Algorithm, determination of the
middle element is important. Binary Search is usually fast and efficient for arrays because
accessing the middle index between two given indices is easy and fast(Time Complexity
O(1)). But memory allocation for the singly linked list is dynamic and non-contiguous,
which makes finding the middle element difficult. One approach could be of using skip list,
one could be traversing the linked list using one pointer.
Prerequisite : Finding middle of a linked list.
Note: The approach and implementation provided below are to show how Binary
Search can be implemented on a linked list. The implementation takes O(n)
time.
Approach :
• 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
Input : Enter value to search : 7
Output : Found
Input : Enter value to search : 12
Output : Not Found
// CPP code to implement binary search
// on Singly Linked List
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node* next;
};
Node *newNode(int x)
{
struct Node* temp = new Node;
temp->data = x;
temp->next = NULL;
return temp;
}
// function to find out middle element
struct Node* middle(Node* start, Node* last)
{
if (start == NULL)
return NULL;
struct Node* slow = start;
struct Node* fast = start -> next;
while (fast != last)
{
fast = fast -> next;
if (fast != last)
{
slow = slow -> next;
fast = fast -> next;
}
}
return slow;
}
84
Chapter 12. Binary Search on Singly Linked List
// Function for implementing the Binary
// Search on linked list
struct Node* binarySearch(Node *head, int value)
{
struct Node* start = head;
struct Node* last = NULL;
do
{
// Find middle
Node* mid = middle(start, last);
// If middle is empty
if (mid == NULL)
return NULL;
// If value is present at middle
if (mid -> data == value)
return mid;
// If value is more than mid
else if (mid -> data < value)
start = mid -> next;
// If the value is less than mid.
else
last = mid;
} while (last == NULL ||
last -> next != start);
// value not present
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
Time Complexity : O(n)
Improved By : sunny94
Source
https://www.geeksforgeeks.org/binary-search-on-singly-linked-list/
86
Chapter 13
Brent’s Cycle Detection
Algorithm
Brent’s Cycle Detection Algorithm - GeeksforGeeks
Given a linked list, check if the the linked list has loop or not. Below diagram shows a linked
list with a loop.
We have discussed Floyd’s algorithm to detect cycle in linked list.
Brent’s cycle detection algorithm is similar to floyd’s algorithm as it also uses two
pointer technique. But there is some difference in their approaches. Here we make one
pointer stationary till every iteration and teleport it to other pointer at every power of
two. The start of the cycle is determined by the smallest power of two at which they
meet. This improves upon the constant factor of Floyd’s algorithm by reducing the number
of calls.
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
4. We reset first_pointer to head and second_pointer to node at position head + length.
5. Now we move both pointers one by one to find beginning of loop.
Comparison with Floyd’s Algorithm:
1) Finds the length of loop in first cycle detection loop itself. No extra work is required for
this.
2) We only move second in every iteration and avoid moving first (which can be costly if
moving to next node involves evaluating a function).
C++
// CPP program to implement Brent's cycle
// detection algorithm to detect cycle in
// a linked list.
#include <stdio.h>
#include <stdlib.h>
/* Link list node */
struct Node {
int data;
struct Node* next;
};
/* This function detects loop in the list
If loop was there in the list then it returns,
the first node of loop otherwise returns NULL */
struct Node* detectCycle(struct Node* head)
{
// if head is null then no loop
if (head == NULL)
return NULL;
struct Node* first_pointer = head;
struct Node* second_pointer = head->next;
int power = 1;
int length = 1;
// This loop runs till we find the loop.
// If there is no loop then second_pointer
// ends at NULL .
while (second_pointer != NULL &&
second_pointer != first_pointer) {
// condition after which we will
// update the power and length as
// smallest power of two gives the
// start of cycle.
if (length == power) {
88
Chapter 13. Brent’s Cycle Detection Algorithm
// updating the power.
power *= 2;
// updating the length
length = 0;
first_pointer = second_pointer;
}
second_pointer = second_pointer->next;
++length;
}
// if it is null then no loop
if (second_pointer == NULL)
return NULL;
// Otherwise length stores actual length
// of loop.
// If needed, we can also print length of
// loop.
// printf("Length of loop is %d\n", length);
// Now set first_pointer to the beginning
// and second_pointer to beginning plus
// cycle length which is length.
first_pointer = second_pointer = head;
while (length > 0) {
second_pointer = second_pointer->next;
--length;
}
// Now move both pointers at same speed so
// that they meet at the beginning of loop.
while (second_pointer != first_pointer) {
second_pointer = second_pointer->next;
first_pointer = first_pointer->next;
}
// If needed, we can also print length of
// loop.
// printf("Length of loop is %d", length);
return first_pointer;
}
struct Node* newNode(int key)
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;
}
// Driver program to test above function
int main()
{
struct Node* head = newNode(50);
head->next = newNode(20);
head->next->next = newNode(15);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(10);
// Create a loop for testing
head->next->next->next->next->next =
head->next->next;
Node *res = detectCycle(head);
if (res == NULL)
printf("No loop");
else
printf("Loop is present at %d", res->data);
return 0;
}
Python3
# Python program to implement
# Brent's cycle detection
# algorithm to detect cycle
# 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:
# Function to initialize head
90
Chapter 13. Brent’s Cycle Detection Algorithm
def __init__(self):
self.head = None
# Function to insert a new Node
# at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Utility function to prit
# the linked LinkedList
def printList(self):
temp = self.head
while(temp):
print (temp.data,end=" ")
temp = temp.next
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
# This loop runs till we
# find the loop. If there
# is no loop then second
# pointer ends at NULL
while (second_p and second_p!= first_p):
# condition after which
# we will update the power
# and length as smallest
# power of two gives
# the start of cycle.
if (length == power):
# updating the power.
power *= 2
# updating the length
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
# Otherwise length stores
# actual length of loop.
# If needed, we can also
# print length of loop.
# print("Length of loop is ")
# print (length)
# Now set first_pointer
# to the beginning and
# second_pointer to
# beginning plus cycle
# length which is length.
first_p = second_p = self.head
while (length > 0):
second_p = second_p.next
length=length-1
# Now move both pointers
# at same speed so that
# they meet at the
# beginning of loop.
while (second_p!= first_p) :
second_p = second_p.next
first_p = first_p.next
return first_p
# Driver program for testing
llist = LinkedList()
llist.push(50)
llist.push(20)
llist.push(15)
llist.push(4)
llist.push(10)
# Create a loop for testing
llist.head.next.next.next.next.next = llist.head.next.next;
res=llist.detectCycle()
92
Chapter 13. Brent’s Cycle Detection Algorithm
if( res.data):
print ("loop found at ",end=' ')
print (res.data)
else :
print ("No Loop ")
# This code is contributed by Gitanjali
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
Bubble Sort On Doubly Linked
List
Bubble Sort On Doubly Linked List - GeeksforGeeks
Sort the given doubly linked list using bubble sort.
Examples:
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.
// CPP program to sort a doubly linked list using
// bubble sort
#include <iostream>
using namespace std;
94
Chapter 14. Bubble Sort On Doubly Linked List
// structure of a node
struct Node {
int data;
Node* prev;
Node* next;
};
/* Function to insert a node at the beginning of a linked list */
void insertAtTheBegin(struct Node **start_ref, int data)
{
struct Node *ptr1 = new Node;
ptr1->data = data;
ptr1->next = *start_ref;
if (*start_ref != NULL)
(*start_ref)->prev = ptr1;
*start_ref = ptr1;
}
/* Function to print nodes in a given linked list */
void printList(struct Node *start)
{
struct Node *temp = start;
cout << endl;
while (temp!=NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
}
/* Bubble sort the given linked list */
void bubbleSort(struct Node *start)
{
int swapped, i;
struct Node *ptr1;
struct Node *lptr = NULL;
/* Checking for empty list */
if (start == NULL)
return;
do
{
swapped = 0;
ptr1 = start;
while (ptr1->next != lptr)
{
95
Chapter 14. Bubble Sort On Doubly Linked List
if (ptr1->data > ptr1->next->data)
{
swap(ptr1->data, ptr1->next->data);
swapped = 1;
}
ptr1 = ptr1->next;
}
lptr = ptr1;
}
while (swapped);
}
int main()
{
int arr[] = {12, 56, 2, 11, 1, 90};
int list_size, i;
/* start with empty linked list */
struct Node *start = NULL;
/* Create linked list from the array arr[].
Created linked list will be 1->11->2->56->12 */
for (i = 0; i< 6; i++)
insertAtTheBegin(&start, arr[i]);
/* print list before sorting */
printf("\n Linked list before sorting ");
printList(start);
/* sort the linked list */
bubbleSort(start);
/* print list after sorting */
printf("\n Linked list after sorting ");
printList(start);
return 0;
}
Output:
Linked list before sorting
90 1 11 2 56 12
Linked list after sorting
1 2 11 12 56 90
96
Chapter 14. Bubble Sort On Doubly Linked List
Source
https://www.geeksforgeeks.org/bubble-sort-on-doubly-linked-list/
97
Chapter 15
C Program for Bubble Sort on
Linked List
C Program for Bubble Sort on Linked List - GeeksforGeeks
Given a singly linked list, sort it using bubble sort.
Input : 10->30->20->5
Output : 5->10->20->30
Input : 20->4->3
Output : 3->4->20
// C program to implement Bubble Sort on singly linked list
#include<stdio.h>
#include<stdlib.h>
/* structure for a node */
struct Node
{
int data;
struct Node *next;
};
/* Function to insert a node at the beginning of a linked list */
void insertAtTheBegin(struct Node **start_ref, int data);
/* Function to bubble sort the given linked list */
void bubbleSort(struct Node *start);
/* Function to swap data of two nodes a and b*/
98
Chapter 15. C Program for Bubble Sort on Linked List
void swap(struct Node *a, struct Node *b);
/* Function to print nodes in a given linked list */
void printList(struct Node *start);
int main()
{
int arr[] = {12, 56, 2, 11, 1, 90};
int list_size, i;
/* start with empty linked list */
struct Node *start = NULL;
/* Create linked list from the array arr[].
Created linked list will be 1->11->2->56->12 */
for (i = 0; i< 6; i++)
insertAtTheBegin(&start, arr[i]);
/* print list before sorting */
printf("\n Linked list before sorting ");
printList(start);
/* sort the linked list */
bubbleSort(start);
/* print list after sorting */
printf("\n Linked list after sorting ");
printList(start);
getchar();
return 0;
}
/* Function to insert a node at the beginning of a linked list */
void insertAtTheBegin(struct Node **start_ref, int data)
{
struct Node *ptr1 = (struct Node*)malloc(sizeof(struct Node));
ptr1->data = data;
ptr1->next = *start_ref;
*start_ref = ptr1;
}
/* Function to print nodes in a given linked list */
void printList(struct Node *start)
{
struct Node *temp = start;
printf("\n");
99
Chapter 15. C Program for Bubble Sort on Linked List
while (temp!=NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}
/* Bubble sort the given linked list */
void bubbleSort(struct Node *start)
{
int swapped, i;
struct Node *ptr1;
struct Node *lptr = NULL;
/* Checking for empty list */
if (start == NULL)
return;
do
{
swapped = 0;
ptr1 = start;
while (ptr1->next != lptr)
{
if (ptr1->data > ptr1->next->data)
{
swap(ptr1, ptr1->next);
swapped = 1;
}
ptr1 = ptr1->next;
}
lptr = ptr1;
}
while (swapped);
}
/* function to swap data of two nodes a and b*/
void swap(struct Node *a, struct Node *b)
{
int temp = a->data;
a->data = b->data;
b->data = temp;
}
Output:
100
Chapter 15. C Program for Bubble Sort on Linked List
Linked list before sorting
90 1 11 2 56 12
Linked list after sorting
1 2 11 12 56 90
Improved By : YugandharTripathi
Source
https://www.geeksforgeeks.org/c-program-bubble-sort-linked-list/
101
Chapter 16
C Program to reverse each node
value in Singly Linked List
C Program to reverse each node value in Singly Linked List - GeeksforGeeks
A linked list is a linear collection of data elements, in which each node points to the next
node. Unlike an array, it doesn’t have upper limit and hence extremely useful.
The task is to access value of each node of linked list and reverse them.
Examples:
Input : 56 87 12 49 35
Output :65 78 21 94 53
Input : 128 87 12433 491 33
Output :821 78 33421 194 33
Algorithm:
The task can be accomplished as:
1. Linearly traverse each node of the singly linked list.
2. Reverse the value of each node.
3. Store the reversed value in the current node.
// C program to reverse every node data in
// singly linked list.
#include <stdio.h>
#include <stdlib.h>
// A linked list node
struct Node {
102
Chapter 16. C Program to reverse each node value in Singly Linked List
int data;
struct Node* next;
};
// newNode function inserts the new node at
// the right side of linked list
struct Node* newNode(int key)
{
struct Node* temp = new Node;
temp->data = key;
temp->next = NULL;
return temp;
}
// reverse() will receive individual data item
// from reverseIndividualData() and will return
// the reversed number to calling function
int reverse(int number)
{
int new_num = 0, rem;
while (number != 0) {
rem = number % 10;
new_num = new_num * 10 + rem;
number = number / 10;
}
return new_num;
}
void reverseIndividualData(struct Node* node)
{
if (node == NULL)
return;
while (node != NULL) {
/* function call to reverse(),
reverseIndividualData(struct Node *node)
will send the one data item at a time to
reverse(node->data) function which will
return updated value to node->data*/
node->data = reverse(node->data);
/* updating node pointer so as to get
next value */
103
Chapter 16. C Program to reverse each node value in Singly Linked List
node = node->next;
}
}
// Function to print nodes in linked list
void printList(struct Node* node)
{
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
// Driver program to test above functions
int main()
{
struct Node* head = NULL;
head = newNode(56);
head->next = newNode(87);
head->next->next = newNode(12);
head->next->next->next = newNode(49);
head->next->next->next->next = newNode(35);
printf("\nList before reversing individual data item \n");
printList(head);
reverseIndividualData(head);
printf("\nList after reversing individual data item\n");
printList(head);
return 0;
}
Output:
List before reversing individual data item
56 87 12 49 35
List after reversing individual data item
65 78 21 94 53
Source
https://www.geeksforgeeks.org/c-program-reverse-node-value-singly-linked-list/
104
Chapter 17
Can we reverse a linked list in
less than O(n)?
Can we reverse a linked list in less than O(n)? - GeeksforGeeks
It doesn’t look possible to reverse asimple singly linked list. A simple singly linked list can
only be reversed in O(n) time using recursive and iterative methods.
A memory efficient doubly linked list with head and tail pointers can also be reversed in
O(1) time by swapping head and tail pointers.
A doubly linked list with head and tail pointers can also be reversed in O(1) time by swapping
head and tail pointers. But we would have to traverse the list in forward direction using
prev pointer and reverse direction using next pointer which may not be considered valid.
This article is contributed by Abhishek. 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/can-we-reverse-a-linked-list-in-less-than-on/
105
Chapter 18
Check if a doubly linked list of
characters is palindrome or not
Check if a doubly linked list of characters is palindrome or not - GeeksforGeeks
Given a doubly linked list of characters, write a function that returns true if the given doubly
linked list is palindrome, else false.
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.
// C++ program to check if doubly
// linked list is palindrome or not
#include<bits/stdc++.h>
using namespace std;
// 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
};
/* Given a reference (pointer to pointer) to
the head of a list and an int, inserts a
new node on the front of the list. */
void push(struct Node** head_ref, char new_data)
{
struct Node* new_node = new Node;
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;
}
// Function to check if list is palindrome or not
bool isPalindrome(struct Node *left)
{
if (left == NULL)
return true;
// Find rightmost node
struct Node *right = left;
while (right->next != NULL)
right = right->next;
while (left != right)
{
if (left->data != right->data)
return false;
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
Time complexity: O(n)
Auxiliary Space : O(1)
Related Post:
• Function to check if a singly linked list is palindrome
• Check if a linked list of strings forms a palindrome
Source
https://www.geeksforgeeks.org/check-doubly-linked-list-characters-palindrome-not/
108
Chapter 19
Check if a linked list is Circular
Linked List
Check if a linked list is Circular Linked List - GeeksforGeeks
Given a singly linked list, find if the linked list is circular or not. A linked list is called
circular if it not NULL terminated and all nodes are connected in the form of a cycle.
Below is an example of circular linked list.
An empty linked list is considered as circular.
Note that this problem is different from cycle detection problem, here all nodes have to be
part of cycle.
The idea is to store head of the linked list and traverse it. If we reach NULL, linked list is
not circular. If reach head again, linked list is circular.
// C++ program to check if linked list is circular
#include<bits/stdc++.h>
using namespace std;
/* Link list Node */
struct Node
{
int data;
struct Node* next;
};
/* This function returns true if given linked
109
Chapter 19. Check if a linked list is Circular Linked List
list is circular, else false. */
bool isCircular(struct Node *head)
{
// An empty linked list is circular
if (head == NULL)
return true;
// Next of head
struct Node *node = head->next;
// This loop would stope in both cases (1) If
// Circular (2) Not circular
while (node != NULL && node != head)
node = node->next;
// If loop stopped because of circular
// condition
return (node == head);
}
// Utility function to create a new node.
Node *newNode(int data)
{
struct Node *temp = new Node;
temp->data = data;
temp->next = NULL;
return temp;
}
/* Drier program to test above function*/
int main()
{
/* Start with the empty list */
struct Node* head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
isCircular(head)? cout << "Yes\n" :
cout << "No\n" ;
// Making linked list circular
head->next->next->next->next = head;
isCircular(head)? cout << "Yes\n" :
cout << "No\n" ;
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
Check if a linked list of strings
forms a palindrome
Check if a linked list of strings forms a palindrome - GeeksforGeeks
Given a linked list handling string data, check to see whether data is palindrome or not?
For example,
Input : a -> bc -> d -> dcb -> a -> NULL
Output : True
String "abcddcba" is palindrome.
Output : a -> bc -> d -> ba -> NULL
Output : False
String "abcdba" is not palindrome.
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++
// Program to check if a given linked list of strings
// form a palindrome
#include <bits/stdc++.h>
using namespace std;
/* Link list node */
struct Node
{
string data;
Node* next;
};
112
Chapter 20. Check if a linked list of strings forms a palindrome
// A utility function to check if str is palindrome
// or not
bool isPalindromeUtil(string str)
{
int length = str.length();
// Match characters from beginning and
// end.
for (int i=0; i<length/2; i++)
if (str[i] != str[length-i-1])
return false;
return true;
}
// Returns true if string formed by linked
// list is palindrome
bool isPalindrome(Node *node)
{
// Append all nodes to form a string
string str = "";
while (node != NULL)
{
str.append(node->data);
node = node->next;
}
// Check if the formed string is palindrome
return isPalindromeUtil(str);
}
// A utility function to print a given linked list
void printList(Node *node)
{
while (node != NULL)
{
cout << node->data << " -> ";
node = node->next;
}
printf("NULL\n");
}
/* Function to create a new node with given data */
Node *newNode(const char *str)
{
Node *new_node = new Node;
new_node->data = str;
113
Chapter 20. Check if a linked list of strings forms a palindrome
new_node->next = NULL;
return new_node;
}
/* Driver program to test above function*/
int main()
{
Node *head = newNode("a");
head->next = newNode("bc");
head->next->next = newNode("d");
head->next->next->next = newNode("dcb");
head->next->next->next->next = newNode("a");
isPalindrome(head)? printf("true\n"):
printf("false\n");
return 0;
}
Java
// Java Program to check if a given linked list of strings
// form a palindrome
import java.util.Scanner;
// Linked List node
class Node
{
String data;
Node next;
Node(String d)
{
data = d;
next = null;
}
}
class LinkedList_Palindrome
{
Node head;
// A utility function to check if str is palindrome
// or not
boolean isPalidromeUtil(String str)
{
int length = str.length();
114
Chapter 20. Check if a linked list of strings forms a palindrome
// Match characters from beginning and
// end.
for (int i=0; i<length/2; i++)
if (str.charAt(i) != str.charAt(length-i-1))
return false;
return true;
}
// Returns true if string formed by linked
// list is palindrome
boolean isPalindrome()
{
Node node = head;
// Append all nodes to form a string
String str = "";
while (node != null)
{
str = str.concat(node.data);
node = node.next;
}
// Check if the formed string is palindrome
return isPalidromeUtil(str);
}
/* Driver program to test above function*/
public static void main(String[] args)
{
LinkedList_Palindrome list = new LinkedList_Palindrome();
list.head = new Node("a");
list.head.next = new Node("bc");
list.head.next.next = new Node("d");
list.head.next.next.next = new Node("dcb");
list.head.next.next.next.next = new Node("a");
System.out.println(list.isPalindrome());
}
}
// This code has been contributed by Amit Khandelwal
Python
# Python program to check if given linked list of
# strings form a palindrome
115
Chapter 20. Check if a linked list of strings forms a palindrome
# Node class
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# A utility function to check if str is palindrome
# or not
def isPalindromeUtil(self, string):
return (string == string[::-1])
# Returns true if string formed by linked list is
# palindrome
def isPalindrome(self):
node = self.head
# Append all nodes to form a string
temp = []
while (node is not None):
temp.append(node.data)
node = node.next
string = "".join(temp)
return self.isPalindromeUtil(string)
# Utility function to print the linked LinkedList
def printList(self):
temp = self.head
while (temp):
print temp.data,
temp = temp.next
# Driver program to test above function
llist = LinkedList()
llist.head = Node('a')
llist.head.next = Node('bc')
llist.head.next.next = Node("d")
llist.head.next.next.next = Node("dcb")
llist.head.next.next.next.next = Node("a")
116
Chapter 20. Check if a linked list of strings forms a palindrome
print "true" if llist.isPalindrome() else "false"
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
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
Check if linked list is sorted
(Iterative and Recursive)
Check if linked list is sorted (Iterative and Recursive) - GeeksforGeeks
Given a Linked List, task is to check whether the Linked List is sorted in Descending order
or not?
Examples :
Input : 8 -> 7 -> 5 -> 2 -> 1
Output : Yes
Explanation :
In given linked list, starting from head,
8 > 7 > 5 > 2 > 1. So, it is sorted in reverse order
Input : 24 -> 12 -> 9 -> 11 -> 8 -> 2
Output : No
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”.
// C++ program to check Linked List is sorted
// in descending order or not
#include <bits/stdc++.h>
using namespace std;
/* Linked list node */
struct Node
{
118
Chapter 21. Check if linked list is sorted (Iterative and Recursive)
int data;
struct Node* next;
};
// function to Check Linked List is
// sorted in descending order or not
bool isSortedDesc(struct Node *head)
{
if (head == NULL)
return true;
// Traverse the list till last node and return
// false if a node is smaller than or equal
// its next.
for (Node *t=head; t->next != NULL; t=t->next)
if (t->data <= t->next->data)
return false;
return true;
}
Node *newNode(int data)
{
Node *temp = new Node;
temp->next = NULL;
temp->data = data;
}
// Driver program to test above
int main()
{
struct Node *head = newNode(7);
head->next = newNode(5);
head->next->next = newNode(4);
head->next->next->next = newNode(3);
isSortedDesc(head) ? cout << "Yes" :
cout << "No";
return 0;
}
Output:
Yes
Time Complexity : O(N), where N is the length of linked list.
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.
// C++ program to recursively check Linked List
// is sorted in descending order or not
#include <bits/stdc++.h>
using namespace std;
/* Linked list node */
struct Node
{
int data;
struct Node* next;
};
// function to Check Linked List is
// sorted in descending order or not
bool isSortedDesc(struct Node *head)
{
// Base cases
if (head == NULL || head->next == NULL)
return true;
// Check first two nodes and recursively
// check remaining.
return (head->data > head->next->data &&
isSortedDesc(head->next));
}
Node *newNode(int data)
{
Node *temp = new Node;
temp->next = NULL;
temp->data = data;
}
// Driver program to test above
int main()
{
struct Node *head = newNode(7);
head->next = newNode(5);
head->next->next = newNode(4);
head->next->next->next = newNode(3);
isSortedDesc(head) ? cout << "Yes" :
cout << "No";
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
Check linked list with a loop is
palindrome or not
Check linked list with a loop is palindrome or not - GeeksforGeeks
Given a linked list with a loop, the task is to find whether it is palindrome or not. You are
not allowed to remove the loop.
Examples:
Input : 1 -> 2 -> 3 -> 2
/|\ \|/
------- 1
Output: Palindrome
Linked list is 1 2 3 2 1 which is a
palindrome.
Input : 1 -> 2 -> 3 -> 4
/|\ \|/
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:
1. Detect the loop using Floyd Cycle Detection Algorithm.
2. Then find the starting node of loop as discussed in this
3. Check linked list is palindrome or not as discussed in this
Below is C++ implementation.
// C++ program to check if a linked list with
// loop is palindrome or not.
#include<bits/stdc++.h>
using namespace std;
/* Link list node */
struct Node
{
int data;
struct Node * next;
};
/* Function to find loop starting node.
loop_node --> Pointer to one of the loop nodes
head --> Pointer to the start node of the linked list */
Node* getLoopstart(Node *loop_node, Node *head)
{
Node *ptr1 = loop_node;
Node *ptr2 = loop_node;
// Count the number of nodes in loop
unsigned int k = 1, i;
while (ptr1->next != ptr2)
{
ptr1 = ptr1->next;
k++;
}
// Fix one pointer to head
ptr1 = head;
// And the other pointer to k nodes after head
ptr2 = head;
for (i = 0; i < k; i++)
123
Chapter 22. Check linked list with a loop is palindrome or not
ptr2 = ptr2->next;
/* Move both pointers at the same pace,
they will meet at loop starting node */
while (ptr2 != ptr1)
{
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}
return ptr1;
}
/* This function detects and find loop starting
node in the list*/
Node* detectAndgetLoopstarting(Node *head)
{
Node *slow_p = head, *fast_p = head,*loop_start;
//Start traversing list and detect loop
while (slow_p && fast_p && fast_p->next)
{
slow_p = slow_p->next;
fast_p = fast_p->next->next;
/* If slow_p and fast_p meet then find
the loop starting node*/
if (slow_p == fast_p)
{
loop_start = getLoopstart(slow_p, head);
break;
}
}
// Return starting node of loop
return loop_start;
}
// Utility function to check if a linked list with loop
// is palindrome with given starting point.
bool isPalindromeUtil(Node *head, Node* loop_start)
{
Node *ptr = head;
stack<int> s;
// Traverse linked list until last node is equal
// to loop_start and store the elements till start
// in a stack
int count = 0;
124
Chapter 22. Check linked list with a loop is palindrome or not
while (ptr != loop_start || count != 1)
{
s.push(ptr->data);
if (ptr == loop_start)
count = 1;
ptr = ptr->next;
}
ptr = head;
count = 0;
// Traverse linked list until last node is
// equal to loop_start second time
while (ptr != loop_start || count != 1)
{
// Compare data of node with the top of stack
// If equal then continue
if (ptr->data == s.top())
s.pop();
// Else return false
else
return false;
if (ptr == loop_start)
count = 1;
ptr = ptr->next;
}
// Return true if linked list is palindrome
return true;
}
// Function to find if linked list is palindrome or not
bool isPalindrome(Node* head)
{
// Find the loop starting node
Node* loop_start = detectAndgetLoopstarting(head);
// Check if linked list is palindrome
return isPalindromeUtil(head, loop_start);
}
Node *newNode(int key)
{
Node *temp = new Node;
temp->data = key;
temp->next = NULL;
return temp;
125
Chapter 22. Check linked list with a loop is palindrome or not
/* Driver program to test above function*/
int main()
{
Node *head = newNode(50);
head->next = newNode(20);
head->next->next = newNode(15);
head->next->next->next = newNode(20);
head->next->next->next->next = newNode(50);
/* Create a loop for testing */
head->next->next->next->next->next = head->next->next;
isPalindrome(head)? cout << "\nPalindrome"
: cout << "\nNot Palindrome";
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
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
Method 1: Count the codes linearly
Traverse the entire Linked List and keep counting the number of nodes. As soon as the loop
is finished, we can check if the count is even or odd. You may try it yourself.
Method 2: Stepping 2 nodes at a time
Approach:
1. Take a pointer and move that pointer two nodes at a time
2. At the end, if the pointer is NULL then length is Even, else Odd.
// C program to check length
// of a given linklist
#include<stdio.h>
#include<stdlib.h>
127
Chapter 23. Check whether the length of given linked list is Even or Odd
// Defining structure
struct Node
{
int data;
struct Node* next;
};
// Function to check the length of linklist
int LinkedListLength(struct Node* head)
{
while (head && head->next)
{
head = head->next->next;
}
if (!head)
return 0;
return 1;
}
// Push function
void push(struct Node** head, int info)
{
// Allocating node
struct Node* node = (struct Node*) malloc(sizeof(struct Node));
// Info into node
node->data = info;
// Next of new node to head
node->next = (*head);
// head points to new node
(*head) = node;
}
// Driver function
int main(void)
{
struct Node* head = NULL;
// Adding elements to Linked List
push(&head, 4);
push(&head, 5);
push(&head, 7);
push(&head, 2);
push(&head, 9);
push(&head, 6);
push(&head, 1);
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);
// Checking for length of
// linklist
if(check == 0)
{
printf("Even\n");
}
else
{
printf("Odd\n");
}
return 0;
}
Output:
Odd
Time Complexity: O(n)
Space Complexity: O(1)
Source
https://www.geeksforgeeks.org/check-whether-the-length-of-given-linked-list-is-even-or-odd/
129
Chapter 24
Circular Linked List | Set 1
(Introduction and Applications)
Circular Linked List | Set 1 (Introduction and Applications) - GeeksforGeeks
We have discussed singly and doubly linked lists in the following posts.
Introduction to Linked List & Insertion
Doubly Linked List Introduction and Insertion
Circular linked list is a linked list where all nodes are connected to form a circle. There
is no NULL at the end. A circular linked list can be a singly circular linked list or doubly
circular linked list.
Advantages of Circular Linked Lists:
1) Any node can be a starting point. We can traverse the whole list by starting from any
point. We just need to stop when the first visited node is visited again.
2) Useful for implementation of queue. Unlike thisimplementation, we don’t need to main-
tain two pointers for front and rear if we use circular linked list. We can maintain a pointer
to the last inserted node and front can always be obtained as next of last.
3) Circular lists are useful in applications to repeatedly go around the list. For example,
when multiple applications are running on a PC, it is common for the operating system to
put the running applications on a list and then to cycle through them, giving each of them
a slice of time to execute, and then making them wait while the CPU is given to another
application. It is convenient for the operating system to use a circular list so that when it
reaches the end of the list it can cycle around to the front of the list.
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
Circular Linked List | Set 2
(Traversal)
Circular Linked List | Set 2 (Traversal) - GeeksforGeeks
We have discussed Circular Linked List Introduction and Applications, in the previous post
on Circular Linked List. In this post, traversal operation is discussed.
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.
/* Function to traverse a given Circular linked list and print nodes */
void printList(struct Node *first)
{
struct Node *temp = first;
// If linked list is not empty
if (first != NULL)
{
// Keep printing nodes till we reach the first node again
do
{
printf("%d ", temp->data);
temp = temp->next;
}
while (temp != first);
132
Chapter 25. Circular Linked List | Set 2 (Traversal)
}
}
Complete C program to demonstrate traversal. Following is complete C program to
demonstrate traversal of circular linked list.
C/C++
#include<stdio.h>
#include<stdlib.h>
/* structure for a node */
struct Node
{
int data;
struct Node *next;
};
/* Function to insert a node at the begining of a Circular
linked list */
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;
/* 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;
}
/* Function to print nodes in a given Circular linked list */
void printList(struct Node *head)
{
struct Node *temp = head;
if (head != NULL)
{
do
{
133
Chapter 25. Circular Linked List | Set 2 (Traversal)
printf("%d ", temp->data);
temp = temp->next;
}
while (temp != head);
}
}
/* Driver program to test above functions */
int main()
{
/* Initialize lists as empty */
struct Node *head = NULL;
/* Created linked list will be 11->2->56->12 */
push(&head, 12);
push(&head, 56);
push(&head, 2);
push(&head, 11);
printf("Contents of Circular Linked List\n ");
printList(head);
return 0;
}
Python
# Python program to demonstrate circular linked list traversal
# Structure for a Node
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
# Constructor to create a empty circular linked list
def __init__(self):
self.head = None
# Function to insert a node at the beginning of a
# circular linked list
def push(self, data):
ptr1 = Node(data)
temp = self.head
134
Chapter 25. Circular Linked List | Set 2 (Traversal)
ptr1.next = self.head
# If linked list is not None then set the next of
# last node
if self.head is not None:
while(temp.next != self.head):
temp = temp.next
temp.next = ptr1
else:
ptr1.next = ptr1 # For the first node
self.head = ptr1
# Function to print nodes in a given circular linked list
def printList(self):
temp = self.head
if self.head is not None:
while(True):
print "%d" %(temp.data),
temp = temp.next
if (temp == self.head):
break
# Driver program to test above function
# Initialize list as empty
cllist = CircularLinkedList()
# Created linked list will be 11->2->56->12
cllist.push(12)
cllist.push(56)
cllist.push(2)
cllist.push(11)
print "Contents of circular Linked List"
cllist.printList()
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Contents of Circular Linked List
11 2 56 12
You may like to see following posts on Circular Linked List
135
Chapter 25. Circular Linked List | Set 2 (Traversal)
Split a Circular Linked List into two halves
Sorted insert for circular linked list
We will soon be discussing implementation of insert delete operations for circular linked
lists.
Source
https://www.geeksforgeeks.org/circular-linked-list-set-2-traversal/
136
Chapter 26
Circular Queue | Set 2 (Circular
Linked List Implementation)
Circular Queue | Set 2 (Circular Linked List Implementation) - GeeksforGeeks
Prerequisite – Circular Singly Linked List
We have discussed basics and how to implement circular queue using array in set 1.
Circular Queue | Set 1 (Introduction and Array Implementation)
In this post another method of circular queue implementation is discussed, using Circular
Singly Linked List.
Operations on Circular Queue:
• Front:Get the front item from queue.
• Rear: Get the last item from queue.
• enQueue(value) This function is used to insert an element into the circular queue.
In a circular queue, the new element is always inserted at Rear position.
1. Create a new node dynamically and insert value into it.
2. Check if front==NULL, if it is true then front = rear = (newly created node)
3. If it is false then rare=(newly created node) and rear node always contains the
address of the front node.
• deQueue() This function is used to delete an element from the circular queue. In a
queue, the element is always deleted from front position.
1. Check whether queue is empty or not means front == NULL.
2. If it is empty then display Queue is empty. If queue is not empty then step 3
3. Check if (front==rear) if it is true then set front = rear = NULL else move
the front forward in queue, update address of front in rear node and return the
element.
137
Chapter 26. Circular Queue | Set 2 (Circular Linked List Implementation)
Elements in Circular Queue are: 14 22 6
Deleted value = 14
Deleted value = 22
Elements in Circular Queue are: 6
Elements in Circular Queue are: 6 9 20
Time Complexity: Time complexity of enQueue(), deQueue() operation is O(1) as there
is no loop in any of the operation.
Note : In case of linked list implementation, a queue can be easily implemented without
being circular. However in case of array implementation, we need a circular queue to save
space.
Source
https://www.geeksforgeeks.org/circular-queue-set-2-circular-linked-list-implementation/
138
Chapter 27
Circular Singly Linked List |
Insertion
Circular Singly Linked List | Insertion - GeeksforGeeks
We have discussed Singly and Circular Linked List in the following post:
Singly Linked List
Circular Linked List
Why Circular? In a singly linked list, for accessing any node of linked list, we start
traversing from the first node. If we are at any node in the middle of the list, then it is
not possible to access nodes that precede the given node. This problem can be solved by
slightly altering the structure of singly linked list. In a singly linked list, next part (pointer
to next node) is NULL, if we utilize this link to point to the first node then we can reach
preceding nodes. Refer this for more advantages of circular linked lists.
The structure thus formed is circular singly linked list look like this:
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:
• Insertion in an empty list
• Insertion at the beginning of the list
• Insertion at the end of the list
• Insertion in between the nodes
Insertion in an empty List
Initially when the list is empty, last pointer will be NULL.
After inserting a node T,
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,
struct Node *addToEmpty(struct Node *last, int data)
{
// This function is only for empty list
if (last != NULL)
return last;
// Creating a node dynamically.
struct Node *last =
(struct Node*)malloc(sizeof(struct Node));
// Assigning the data.
last -> data = data;
// Note : list was empty. We link single node
// to itself.
last -> next = last;
return last;
}
Insertion at the beginning of the list
To Insert a node at the beginning of the list, follow these step:
1. Create a node, say T.
141
Chapter 27. Circular Singly Linked List | Insertion
2. Make T -> next = last -> next.
3. last -> next = T.
After insertion,
Function to insert node in the beginning of the List,
struct Node *addBegin(struct Node *last, int data)
{
if (last == NULL)
return addToEmpty(last, data);
// Creating a node dynamically.
struct Node *temp
= (struct Node *)malloc(sizeof(struct Node));
// Assigning the data.
temp -> data = data;
// Adjusting the links.
temp -> next = last -> next;
last -> next = temp;
return last;
}
142
Chapter 27. Circular Singly Linked List | Insertion
Insertion at the end of the list
To Insert a node at the end of the list, follow these step:
1. Create a node, say T.
2. Make T -> next = last -> next;
3. last -> next = T.
4. last = T.
After insertion,
Function to insert node in the end of the List,
struct Node *addEnd(struct Node *last, int data)
{
if (last == NULL)
return addToEmpty(last, data);
// Creating a node dynamically.
struct Node *temp =
(struct Node *)malloc(sizeof(struct Node));
// Assigning the data.
temp -> data = data;
// Adjusting the links.
143
Chapter 27. Circular Singly Linked List | Insertion
temp -> next = last -> next;
last -> next = temp;
last = temp;
return last;
}
Insertion in between the nodes
To Insert a node at the end of the list, follow these step:
1. Create a node, say T.
2. Search the node after which T need to be insert, say that node be P.
3. Make T -> next = P -> next;
4. P -> next = T.
Suppose 12 need to be insert after node having value 10,
After searching and insertion,
Function to insert node in the end of the List,
struct Node *addAfter(struct Node *last, int data, int item)
{
if (last == NULL)
return NULL;
struct Node *temp, *p;
144
Chapter 27. Circular Singly Linked List | Insertion
p = last -> next;
// Searching the item.
do
{
if (p ->data == item)
{
// Creating a node dynamically.
temp = (struct Node *)malloc(sizeof(struct Node));
// Assigning the data.
temp -> data = data;
// Adjusting the links.
temp -> next = p -> next;
// Adding newly allocated node after p.
p -> next = temp;
// Checking for the last node.
if (p == last)
last = temp;
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;
};
struct Node *addToEmpty(struct Node *last, int data)
{
// This function is only for empty list
if (last != NULL)
145
Chapter 27. Circular Singly Linked List | Insertion
return last;
// Creating a node dynamically.
struct Node *temp =
(struct Node*)malloc(sizeof(struct Node));
// Assigning the data.
temp -> data = data;
last = temp;
// Creating the link.
last -> next = last;
return last;
}
struct Node *addBegin(struct Node *last, int data)
{
if (last == NULL)
return addToEmpty(last, data);
struct Node *temp =
(struct Node *)malloc(sizeof(struct Node));
temp -> data = data;
temp -> next = last -> next;
last -> next = temp;
return last;
}
struct Node *addEnd(struct Node *last, int data)
{
if (last == NULL)
return addToEmpty(last, data);
struct Node *temp =
(struct Node *)malloc(sizeof(struct Node));
temp -> data = data;
temp -> next = last -> next;
last -> next = temp;
last = temp;
return last;
}
struct Node *addAfter(struct Node *last, int data, int item)
146
Chapter 27. Circular Singly Linked List | Insertion
{
if (last == NULL)
return NULL;
struct Node *temp, *p;
p = last -> next;
do
{
if (p ->data == item)
{
temp = (struct Node *)malloc(sizeof(struct Node));
temp -> data = data;
temp -> next = p -> next;
p -> next = temp;
if (p == last)
last = temp;
return last;
}
p = p -> next;
} while(p != last -> next);
cout << item << " not present in the list." << endl;
return last;
void traverse(struct Node *last)
{
struct Node *p;
// If list is empty, return.
if (last == NULL)
{
cout << "List is empty." << endl;
return;
}
// Pointing to first Node of the list.
p = last -> next;
// Traversing the list.
do
{
cout << p -> data << " ";
p = p -> next;
147
Chapter 27. Circular Singly Linked List | Insertion
while(p != last->next);
// Driven Program
int main()
{
struct Node *last = NULL;
last = addToEmpty(last, 6);
last = addBegin(last, 4);
last = addBegin(last, 2);
last = addEnd(last, 8);
last = addEnd(last, 12);
last = addAfter(last, 10, 8);
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
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:
Input : Head of the below linked list
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
original->next->random= original->random->next; /*TRAVERSE
TWO NODES*/
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;
• Ensure that original->next is NULL and return the cloned list
Below is the C++ implementation.
// C++ program to clone a linked list with next
// and arbit pointers in O(n) time
#include <bits/stdc++.h>
using namespace std;
// Structure of linked list Node
struct Node
{
int data;
Node *next,*random;
Node(int x)
{
data = x;
next = random = NULL;
}
};
// Utility function to print the list.
void print(Node *start)
{
Node *ptr = start;
while (ptr)
{
cout << "Data = " << ptr->data << ", Random = "
<< ptr->random->data << endl;
ptr = ptr->next;
}
}
// This function clones a given linked list
// in O(1) space
Node* clone(Node *start)
{
Node* curr = start, *temp;
// insert additional node after
150
Chapter 28. Clone a linked list with next and random pointer in O(1) space
// every node of original list
while (curr)
{
temp = curr->next;
// Inserting node
curr->next = new Node(curr->data);
curr->next->next = temp;
curr = temp;
}
curr = start;
// adjust the random pointers of the
// newly added nodes
while (curr)
{
curr->next->random = curr->random->next;
// move to the next newly added node by
// skipping an original node
curr = curr->next?curr->next->next:curr->next;
}
Node* original = start, *copy = start->next;
// save the start of copied linked list
temp = copy;
// now separate the original list and copied list
while (original && copy)
{
original->next =
original->next? original->next->next : original->next;
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
start->next->next = new Node(3);
start->next->next->next = new Node(4);
start->next->next->next->next = new Node(5);
// 1's random points to 3
start->random = start->next->next;
// 2's random points to 1
start->next->random = start;
// 3's and 4's random points to 5
start->next->next->random =
start->next->next->next->next;
start->next->next->next->random =
start->next->next->next->next;
// 5's random points to 2
start->next->next->next->next->random =
start->next;
cout << "Original list : \n";
print(start);
cout << "\nCloned list : \n";
Node *cloned_list = clone(start);
print(cloned_list);
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
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
in copy linked list.
Following diagram shows status of both Linked Lists after above 3 steps. The red arrow
shows arbit pointers and black arrow shows next pointers.
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
original->next->arbitrary = original->arbitrary->next; /*TRAVERSE
TWO NODES*/
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;
4) Make sure that last element of original->next is NULL.
Refer below post for implementation of this method.
Clone a linked list with next and random pointer in O(1) space
Time Complexity: O(n)
Auxiliary Space: O(1)
Refer Following Post for Hashing based Implementation.
Clone a linked list with next and random pointer | Set 2
Asked by Varun Bhatia. 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/a-linked-list-with-next-and-arbit-pointer/
156
Chapter 30
Clone a linked list with next
and random pointer | Set 2
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++
// C++ program to clone a linked list with
// random pointers
#include<bits/stdc++.h>
using namespace std;
// Linked List Node
class Node
{
public:
int data;//Node data
// Next and random reference
Node *next, *random;
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;
}
};
// linked list class
class LinkedList
{
public:
Node *head;// Linked list head reference
LinkedList(Node *head)
{
this->head = head;
}
// push method to put data always at
// the head in the linked list.
void push(int data)
{
Node *node = new Node(data);
node->next = head;
head = node;
}
// Method to print the list.
void print()
{
Node *temp = head;
while (temp != NULL)
{
Node *random = temp->random;
int randomData = (random != NULL)?
random->data: -1;
cout << "Data = " << temp->data
<< ", ";
cout << "Random Data = " <<
randomData << endl;
temp = temp->next;
}
cout << endl;
}
// Actual clone method which returns
// head reference of cloned linked
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;
// Hash map which contains node
// to node mapping of original
// and clone linked list.
unordered_map<Node*, Node*> mymap;
// Traverse the original list and
// make a copy of that in the
// clone linked list.
while (origCurr != NULL)
{
cloneCurr = new Node(origCurr->data);
mymap[origCurr] = cloneCurr;
origCurr = origCurr->next;
}
// Adjusting the original list
// reference again.
origCurr = head;
// Traversal of original list again
// to adjust the next and random
// references of clone list using
// hash map.
while (origCurr != NULL)
{
cloneCurr = mymap[origCurr];
cloneCurr->next = mymap[origCurr->next];
cloneCurr->random = mymap[origCurr->random];
origCurr = origCurr->next;
}
// return the head reference of
// the clone list.
return new LinkedList(mymap[head]);
}
};
// driver code
int main()
{
159
Chapter 30. Clone a linked list with next and random pointer | Set 2
// Pushing data in the linked list.
LinkedList *mylist = new LinkedList(new Node(5));
mylist->push(4);
mylist->push(3);
mylist->push(2);
mylist->push(1);
// Setting up random references.
mylist->head->random = mylist->head->next->next;
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;
// Making a clone of the original
// linked list.
LinkedList *clone = mylist->clone();
// Print the original and cloned
// linked list.
cout << "Original linked list\n";
mylist->print();
cout << "\nCloned linked list\n";
clone->print();
}
// This code is contributed by Chhavi
Java
// Java program to clone a linked list with random pointers
import java.util.HashMap;
import java.util.Map;
// Linked List Node class
class Node
{
int data;//Node data
Node next, random;//Next and random reference
//Node constructor
160
Chapter 30. Clone a linked list with next and random pointer | Set 2
public Node(int data)
{
this.data = data;
this.next = this.random = null;
}
}
// linked list class
class LinkedList
{
Node head;//Linked list head reference
// Linked list constructor
public LinkedList(Node head)
{
this.head = head;
}
// push method to put data always at the head
// in the linked list.
public void push(int data)
{
Node node = new Node(data);
node.next = this.head;
this.head = node;
}
// Method to print the list.
void print()
{
Node temp = head;
while (temp != null)
{
Node random = temp.random;
int randomData = (random != null)? random.data: -1;
System.out.println("Data = " + temp.data +
", Random data = "+ randomData);
temp = temp.next;
}
}
// Actual clone method which returns head
// reference of cloned linked list.
public LinkedList clone()
{
// Initialize two references, one with original
// list's head.
Node origCurr = this.head, cloneCurr = null;
161
Chapter 30. Clone a linked list with next and random pointer | Set 2
// Hash map which contains node to node mapping of
// original and clone linked list.
Map<Node, Node> map = new HashMap<Node, Node>();
// Traverse the original list and make a copy of that
// in the clone linked list.
while (origCurr != null)
{
cloneCurr = new Node(origCurr.data);
map.put(origCurr, cloneCurr);
origCurr = origCurr.next;
}
// Adjusting the original list reference again.
origCurr = this.head;
// Traversal of original list again to adjust the next
// and random references of clone list using hash map.
while (origCurr != null)
{
cloneCurr = map.get(origCurr);
cloneCurr.next = map.get(origCurr.next);
cloneCurr.random = map.get(origCurr.random);
origCurr = origCurr.next;
}
//return the head reference of the clone list.
return new LinkedList(map.get(this.head));
}
}
// 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);
// Setting up random references.
list.head.random = list.head.next.next;
list.head.next.random =
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;
// Making a clone of the original linked list.
LinkedList clone = list.clone();
// Print the original and cloned linked list.
System.out.println("Original linked list");
list.print();
System.out.println("\nCloned linked list");
clone.print();
}
}
Output:
Original linked list
Data = 1, Random data = 3
Data = 2, Random data = 4
Data = 3, Random data = 5
Data = 4, Random data = -1
Data = 5, Random data = 2
Cloned linked list
Data = 1, Random data = 3
Data = 2, Random data = 4
Data = 3, Random data = 5
Data = 4, Random data = -1
Data = 5, Random data = 2
Time complexity : O(n)
Auxiliary space : O(n)
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/clone-linked-list-next-arbit-pointer-set-2/
163
Chapter 31
Compare two strings
represented as linked lists
Compare two strings represented as linked lists - GeeksforGeeks
Given two linked lists, represented as linked lists (every character is a node in linked list).
Write a function compare() that works similar to strcmp(), i.e., it returns 0 if both strings
are same, 1 if first linked list is lexicographically greater, and -1 if second string is lexico-
graphically greater.
Examples:
Input: list1 = g->e->e->k->s->a
list2 = g->e->e->k->s->b
Output: -1
Input: list1 = g->e->e->k->s->a
list2 = g->e->e->k->s
Output: 1
Input: list1 = g->e->e->k->s
list2 = g->e->e->k->s
Output: 0
C++
// C++ program to compare two strings represented as linked
// lists
#include<bits/stdc++.h>
using namespace std;
// Linked list Node structure
164
Chapter 31. Compare two strings represented as linked lists
struct Node
{
char c;
struct Node *next;
};
// Function to create newNode in a linkedlist
Node* newNode(char c)
{
Node *temp = new Node;
temp->c = c;
temp->next = NULL;
return temp;
};
int compare(Node *list1, Node *list2)
{
// Traverse both lists. Stop when either end of a linked
// list is reached or current characters don't match
while (list1 && list2 && list1->c == list2->c)
{
list1 = list1->next;
list2 = list2->next;
}
// If both lists are not empty, compare mismatching
// characters
if (list1 && list2)
return (list1->c > list2->c)? 1: -1;
// If either of the two lists has reached end
if (list1 && !list2) return 1;
if (list2 && !list1) return -1;
// If none of the above conditions is true, both
// lists have reached end
return 0;
}
// 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
Node *list2 = newNode('g');
list2->next = newNode('e');
list2->next->next = newNode('e');
list2->next->next->next = newNode('k');
list2->next->next->next->next = newNode('s');
list2->next->next->next->next->next = newNode('a');
cout << compare(list1, list2);
return 0;
}
Java
// Java program to compare two strings represented as a linked list
// Linked List Class
class LinkedList {
Node head; // head of list
static Node a, b;
/* Node Class */
static class Node {
char data;
Node next;
// Constructor to create a new node
Node(char d) {
data = d;
next = null;
}
}
int compare(Node node1, Node node2) {
if (node1 == null && node2 == null) {
return 1;
}
while (node1 != null && node2 != null && node1.data == node2.data) {
node1 = node1.next;
node2 = node2.next;
}
// if the list are diffrent in size
if (node1 != null && node2 != null) {
166
Chapter 31. Compare two strings represented as linked lists
return (node1.data > node2.data ? 1 : -1);
}
// if either of the list has reached end
if (node1 != null && node2 == null) {
return 1;
}
if (node1 == null && node2 != null) {
return -1;
}
return 0;
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
Node result = null;
list.a = new Node('g');
list.a.next = new Node('e');
list.a.next.next = new Node('e');
list.a.next.next.next = new Node('k');
list.a.next.next.next.next = new Node('s');
list.a.next.next.next.next.next = new Node('b');
list.b = new Node('g');
list.b.next = new Node('e');
list.b.next.next = new Node('e');
list.b.next.next.next = new Node('k');
list.b.next.next.next.next = new Node('s');
list.b.next.next.next.next.next = new Node('a');
int value;
value = list.compare(a, b);
System.out.println(value);
}
}
// This code has been contributed by Mayank Jaiswal
Python
# Python program to compare two strings represented as
# linked lists
# A linked list node structure
class Node:
167
Chapter 31. Compare two strings represented as linked lists
# Constructor to create a new node
def __init__(self, key):
self.c = key ;
self.next = None
def compare(list1, list2):
# Traverse both lists. Stop when either end of linked
# list is reached or current characters don't watch
while(list1 and list2 and list1.c == list2.c):
list1 = list1.next
list2 = list2.next
# If both lists are not empty, compare mismatching
# characters
if(list1 and list2):
return 1 if list1.c > list2.c else -1
# If either of the two lists has reached end
if (list1 and not list2):
return 1
if (list2 and not list1):
return -1
return 0
# 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')
print compare(list1, list2)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
168
Chapter 31. Compare two strings represented as linked lists
Thanks to Gaurav Ahirwar for suggesting above implementation.
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
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++
// C++ program to construct the maximum sum linked
// list out of two given sorted lists
#include<iostream>
using namespace std;
//A linked list node
struct Node
{
int data; //data belong to that node
Node *next; //next pointer
};
// Push the data to the head of the linked list
void push(Node **head, int data)
{
//Alocation memory to the new node
Node *newnode = new Node;
//Assigning data to the new node
newnode->data = data;
//Adjusting next pointer of the new node
newnode->next = *head;
//New node becomes the head of the list
*head = newnode;
}
// Method that adjusts the pointers and prints the final list
void finalMaxSumList(Node *a, Node *b)
{
Node *result = NULL;
// Assigning pre and cur to the head of the
// linked list.
Node *pre1 = a, *curr1 = a;
Node *pre2 = b, *curr2 = b;
// Till either of the current pointers is not
// NULL execute the loop
while (curr1 != NULL || curr2 != 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;
// Calculating sum by traversing the nodes of linked
// list as the merging of two linked list. The loop
// stops at a common node
while (curr1!=NULL && curr2!=NULL && curr1->data!=curr2->data)
{
if (curr1->data < curr2->data)
{
sum1 += curr1->data;
curr1 = curr1->next;
}
else // (curr2->data < curr1->data)
{
sum2 += curr2->data;
curr2 = curr2->next;
}
}
// If either of current pointers becomes NULL
// carry on the sum calculation for other one.
if (curr1 == NULL)
{
while (curr2 != NULL)
{
sum2 += curr2->data;
curr2 = curr2->next;
}
}
if (curr2 == NULL)
{
while (curr1 != NULL)
{
sum1 += curr1->data;
curr1 = curr1->next;
}
}
// First time adjustment of resultant head based on
// the maximum sum.
if (pre1 == a && pre2 == b)
result = (sum1 > sum2)? pre1 : pre2;
// If pre1 and pre2 don't contain the head pointers of
172
Chapter 32. Construct a Maximum Sum Linked List out of two Sorted Linked Lists having
some Common nodes
// lists adjust the next pointers of previous pointers.
else
{
if (sum1 > sum2)
pre2->next = pre1->next;
else
pre1->next = pre2->next;
}
// Adjusting previous pointers
pre1 = curr1, pre2 = curr2;
// If curr1 is not NULL move to the next.
if (curr1)
curr1 = curr1->next;
// If curr2 is not NULL move to the next.
if (curr2)
curr2 = curr2->next;
}
// Print the resultant list.
while (result != NULL)
{
cout << result->data << " ";
result = result->next;
}
}
//Main driver program
int main()
{
//Linked List 1 : 1->3->30->90->110->120->NULL
//Linked List 2 : 0->3->12->32->90->100->120->130->NULL
Node *head1 = NULL, *head2 = NULL;
push(&head1, 120);
push(&head1, 110);
push(&head1, 90);
push(&head1, 30);
push(&head1, 3);
push(&head1, 1);
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
// Java program to construct a Maximum Sum Linked List out of
// two Sorted Linked Lists having some Common nodes
class LinkedList
{
Node head; // head of list
/* Linked list Node*/
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
// Method to adjust pointers and print final list
void finalMaxSumList(Node a, Node b)
{
Node result = null;
/* assigning pre and cur to head
of the linked list */
Node pre1 = a, curr1 = a;
Node pre2 = b, curr2 = b;
/* Till either of current pointers is not null
execute the loop */
while (curr1 != null || curr2 != null)
{
// Keeping 2 local variables at the start of every
// loop run to keep track of the sum between pre
// and cur reference elements.
int sum1 = 0, sum2 = 0;
// Calculating sum by traversing the nodes of linked
// list as the merging of two linked list. The loop
// stops at a common node
174
Chapter 32. Construct a Maximum Sum Linked List out of two Sorted Linked Lists having
some Common nodes
while (curr1 != null && curr2 != null &&
curr1.data != curr2.data)
{
if (curr1.data<curr2.data)
{
sum1 += curr1.data;
curr1 = curr1.next;
}
else
{
sum2 += curr2.data;
curr2 = curr2.next;
}
}
// If either of current pointers becomes null
// carry on the sum calculation for other one.
if (curr1 == null)
{
while (curr2 != null)
{
sum2 += curr2.data;
curr2 = curr2.next;
}
}
if (curr2 == null)
{
while(curr1 != null)
{
sum1 += curr1.data;
curr1 = curr1.next;
}
}
// First time adjustment of resultant head based on
// the maximum sum.
if (pre1 == a && pre2 == b)
result = (sum1 > sum2) ? pre1 : pre2;
// If pre1 and pre2 don't contain the head refernces of
// lists adjust the next pointers of previous pointers.
else
{
if (sum1 > sum2)
pre2.next = pre1.next;
else
pre1.next = pre2.next;
175
Chapter 32. Construct a Maximum Sum Linked List out of two Sorted Linked Lists having
some Common nodes
// Adjusting previous pointers
pre1 = curr1;
pre2 = curr2;
// If curr1 is not NULL move to the next.
if (curr1 != null)
curr1 = curr1.next;
// If curr2 is not NULL move to the next.
if (curr2 != null)
curr2 = curr2.next;
}
while (result != null)
{
System.out.print(result.data + " ");
result = result.next;
}
System.out.println();
}
/* Inserts a node at start of linked list */
void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
/* Drier program to test above functions */
public static void main(String args[])
{
LinkedList llist1 = new LinkedList();
LinkedList llist2 = new LinkedList();
//Linked List 1 : 1->3->30->90->110->120->NULL
//Linked List 2 : 0->3->12->32->90->100->120->130->NULL
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
# Python program to construct a Maximum Sum Linked List out of
# two Sorted Linked Lists having some Common nodes
class LinkedList(object):
def __init__(self):
# head of list
self.head = None
# Linked list Node
class Node(object):
def __init__(self, d):
self.data = d
self.next = None
# Method to adjust pointers and print final list
def finalMaxSumList(self, a, b):
result = None
# assigning pre and cur to head
# of the linked list
pre1 = a
curr1 = a
pre2 = b
curr2 = b
# Till either of current pointers is not null
# execute the loop
while curr1 != None or curr2 != None:
# Keeping 2 local variables at the start of every
# loop run to keep track of the sum between pre
177
Chapter 32. Construct a Maximum Sum Linked List out of two Sorted Linked Lists having
some Common nodes
# and cur reference elements.
sum1 = 0
sum2 = 0
# Calculating sum by traversing the nodes of linked
# list as the merging of two linked list. The loop
# stops at a common node
while curr1 != None and curr2 != None and curr1.data != curr2.data:
if curr1.data < curr2.data:
sum1 += curr1.data
curr1 = curr1.next
else:
sum2 += curr2.data
curr2 = curr2.next
# If either of current pointers becomes null
# carry on the sum calculation for other one.
if curr1 == None:
while curr2 != None:
sum2 += curr2.data
curr2 = curr2.next
if curr2 == None:
while curr1 != None:
sum1 += curr1.data
curr1 = curr1.next
# First time adjustment of resultant head based on
# the maximum sum.
if pre1 == a and pre2 == b:
result = pre1 if (sum1 > sum2) else pre2
else:
# If pre1 and pre2 don't contain the head refernces of
# lists adjust the next pointers of previous pointers.
if sum1 > sum2:
pre2.next = pre1.next
else:
pre1.next = pre2.next
# Adjusting previous pointers
pre1 = curr1
pre2 = curr2
# If curr1 is not NULL move to the next.
if curr1 != None:
curr1 = curr1.next
# If curr2 is not NULL move to the next.
if curr2 != None:
curr2 = curr2.next
while result != None:
print str(result.data),
result = result.next
print ''
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()
# Linked List 1 : 1->3->30->90->110->120->NULL
# Linked List 2 : 0->3->12->32->90->100->120->130->NULL
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)
# This code is contributed by BHAVYA JAIN
Output:
1 3 12 32 90 110 120 130
Time complexity = O(n) where n is the length of bigger linked list
Auxiliary space = O(1)
However a problem in this solution is that the original lists are changed.
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
Construct a linked list from 2D
matrix
Construct a linked list from 2D matrix - GeeksforGeeks
Given a matrix. Convert it into a linked list matrix such that each node is connected to its
next right and down node.
Example:
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
Question Source : Factset Interview Experience | Set 9
The idea is to construct a new node for every element of matrix and recursively create its
down and right nodes.
C++
181
Chapter 33. Construct a linked list from 2D matrix
// CPP program to construct a linked list
// from given 2D matrix
#include <bits/stdc++.h>
using namespace std;
// struct node of linked list
struct Node {
int data;
Node* right, *down;
};
// returns head pointer of linked list
// constructed from 2D matrix
Node* construct(int arr[][3], int i, int j,
int m, int n)
{
// return if i or j is out of bounds
if (i > n - 1 || j > m - 1)
return NULL;
// create a new node for current i and j
// and recursively allocate its down and
// right pointers
Node* temp = new Node();
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;
}
// utility function for displaying
// linked list data
void display(Node* head)
{
// pointer to move right
Node* Rp;
// pointer to move down
Node* Dp = head;
// loop till node->down is not NULL
while (Dp) {
Rp = Dp;
// loop till node->right is not NULL
while (Rp) {
cout << Rp->data << " ";
Rp = Rp->right;
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
// Java program to construct a linked list
// from given 2D matrix
public class Linked_list_2D_Matrix {
// node of linked list
static class Node {
int data;
Node right;
Node down;
};
// returns head pointer of linked list
// constructed from 2D matrix
static Node construct(int arr[][], int i, int j,
int m, int n) {
// return if i or j is out of bounds
if (i > n - 1 || j > m - 1)
return null;
// create a new node for current i and j
// and recursively allocate its down and
// right pointers
Node temp = new Node();
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;
}
// utility function for displaying
// linked list data
static void display(Node head) {
// pointer to move right
Node Rp;
// pointer to move down
Node Dp = head;
// loop till node->down is not NULL
while (Dp != null) {
Rp = Dp;
// loop till node->right is not NULL
while (Rp != null) {
System.out.print(Rp.data + " ");
Rp = Rp.right;
}
System.out.println();
Dp = Dp.down;
}
}
// 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
Construct a linked list from 2D
matrix (Iterative Approach)
Construct a linked list from 2D matrix (Iterative Approach) - GeeksforGeeks
Given a matrix, the task is to construct a linked list matrix in which each node is connected
to its right and down node.
Example:
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.
Below is the implementation of the above approach:
// C++ program to construct a linked
// list from 2D matrix | Iterative Approach
#include <bits/stdc++.h>
using namespace std;
// struct node of linked list
struct node {
int data;
node *right, *down;
};
// utility function to create a new node with given data
node* newNode(int d)
{
node* temp = new node;
temp->data = d;
temp->right = temp->down = NULL;
return temp;
}
187
Chapter 34. Construct a linked list from 2D matrix (Iterative Approach)
// utility function to print the linked list pointed to by head pointer
void display(node* head)
{
node *rp, *dp = head;
// loop until the down pointer is not NULL
while (dp) {
rp = dp;
// loop until the right pointer is not NULL
while (rp) {
cout << rp->data << " ";
rp = rp->right;
}
cout << endl;
dp = dp->down;
}
}
// function which constructs the linked list
// from the given matrix of size m * n
// and returns the head pointer of the linked list
node* constructLinkedMatrix(int mat[][3], int m, int n)
{
// stores the head of the linked list
node* mainhead = NULL;
// stores the head of linked lists of each row
node* head[m];
node *righttemp, *newptr;
// Firstly, we create m linked lists
// by setting all the right nodes of every row
for (int i = 0; i < m; i++) {
// initially set the head of ith row as NULL
head[i] = NULL;
for (int j = 0; j < n; j++) {
newptr = newNode(mat[i][j]);
// stores the mat[0][0] node as
// the mainhead of the linked list
if (!mainhead)
mainhead = newptr;
if (!head[i])
head[i] = newptr;
else
188
Chapter 34. Construct a linked list from 2D matrix (Iterative Approach)
righttemp->right = newptr;
righttemp = newptr;
}
}
// Then, for every ith and (i+1)th list,
// we set the down pointers of
// every node of ith list
// with its corresponding
// node of (i+1)th list
for (int i = 0; i < m - 1; i++) {
node *temp1 = head[i], *temp2 = head[i + 1];
while (temp1 && temp2) {
temp1->down = temp2;
temp1 = temp1->right;
temp2 = temp2->right;
}
}
// return the mainhead pointer of the linked list
return mainhead;
}
// Driver program to test the above function
int main()
{
int m, n; // m = rows and n = columns
m = 3, n = 3;
// 2D matrix
int mat[][3] = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
node* head = constructLinkedMatrix(mat, m, n);
display(head);
return 0;
}
Output:
1 2 3
4 5 6
189
Chapter 34. Construct a linked list from 2D matrix (Iterative Approach)
7 8 9
Time complexity: O(M * N)
Improved By : souravdutta123
Source
https://www.geeksforgeeks.org/construct-a-linked-list-from-2d-matrix-iterative-approach/
190
Chapter 35
Convert a Binary Tree to a
Circular Doubly Link List
Convert a Binary Tree to a Circular Doubly Link List - GeeksforGeeks
Given a Binary Tree, convert it to a Circular Doubly Linked List (In-Place).
• 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
The idea can be described using below steps.
1) Write a general purpose function that concatenates two given circular doubly lists (This
function is explained below).
2) Now traverse the given tree
….a) Recursively convert left subtree to a circular DLL. Let the converted list be leftList.
….a) Recursively convert right subtree to a circular DLL. Let the converted list be rightList.
….c) Make a circular linked list of root of the tree, make left and right of root to point to
itself.
….d) Concatenate leftList with list of single root node.
….e) Concatenate the list produced in step above (d) with rightList.
Note that the above code traverses tree in Postorder fashion. We can traverse in inorder
fashion also. We can first concatenate left subtree and root, then recur for right subtree
and concatenate the result with left-root concatenation.
192
Chapter 35. Convert a Binary Tree to a Circular Doubly Link List
How to Concatenate two circular DLLs?
• 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.
Below are implementations of above idea.
C++
// C++ Program to convert a Binary Tree
// to a Circular Doubly Linked List
#include<iostream>
using namespace std;
// To represents a node of a Binary Tree
struct Node
{
struct Node *left, *right;
int data;
};
// A function that appends rightList at the end
// of leftList.
Node *concatenate(Node *leftList, Node *rightList)
{
// If either of the list is empty
// then return the other list
if (leftList == NULL)
return rightList;
if (rightList == NULL)
return leftList;
// Store the last Node of left List
Node *leftLast = leftList->left;
// Store the last Node of right List
Node *rightLast = rightList->left;
// Connect the last node of Left List
// with the first Node of the right List
leftLast->right = rightList;
rightList->left = leftLast;
// Left of first node points to
// the last node in the list
193
Chapter 35. Convert a Binary Tree to a Circular Doubly Link List
leftList->left = rightLast;
// Right of last node refers to the first
// node of the List
rightLast->right = leftList;
return leftList;
}
// Function converts a tree to a circular Linked List
// and then returns the head of the Linked List
Node *bTreeToCList(Node *root)
{
if (root == NULL)
return NULL;
// Recursively convert left and right subtrees
Node *left = bTreeToCList(root->left);
Node *right = bTreeToCList(root->right);
// Make a circular linked list of single node
// (or root). To do so, make the right and
// left pointers of this node point to itself
root->left = root->right = root;
// Step 1 (concatenate the left list with the list
// with single node, i.e., current node)
// Step 2 (concatenate the returned list with the
// right List)
return concatenate(concatenate(left, root), right);
}
// Display Circular Link List
void displayCList(Node *head)
{
cout << "Circular Linked List is :\n";
Node *itr = head;
do
{
cout << itr->data <<" ";
itr = itr->right;
} while (head!=itr);
cout << "\n";
}
// Create a new Node and return its address
Node *newNode(int data)
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;
}
// Driver Program to test above function
int main()
{
Node *root = newNode(10);
root->left = newNode(12);
root->right = newNode(15);
root->left->left = newNode(25);
root->left->right = newNode(30);
root->right->left = newNode(36);
Node *head = bTreeToCList(root);
displayCList(head);
return 0;
}
Java
// Java Program to convert a Binary Tree to a
// Circular Doubly Linked List
// Node class represents a Node of a Tree
class Node
{
int val;
Node left,right;
public Node(int val)
{
this.val = val;
left = right = null;
}
}
// A class to represent a tree
class Tree
{
Node root;
public Tree()
{
root = null;
195
Chapter 35. Convert a Binary Tree to a Circular Doubly Link List
// concatenate both the lists and returns the head
// of the List
public Node concatenate(Node leftList,Node rightList)
{
// If either of the list is empty, then
// return the other list
if (leftList == null)
return rightList;
if (rightList == null)
return leftList;
// Store the last Node of left List
Node leftLast = leftList.left;
// Store the last Node of right List
Node rightLast = rightList.left;
// Connect the last node of Left List
// with the first Node of the right List
leftLast.right = rightList;
rightList.left = leftLast;
// left of first node refers to
// the last node in the list
leftList.left = rightLast;
// Right of last node refers to the first
// node of the List
rightLast.right = leftList;
// Return the Head of the List
return leftList;
}
// Method converts a tree to a circular
// Link List and then returns the head
// of the Link List
public Node bTreeToCList(Node root)
{
if (root == null)
return null;
// Recursively convert left and right subtrees
Node left = bTreeToCList(root.left);
Node right = bTreeToCList(root.right);
196
Chapter 35. Convert a Binary Tree to a Circular Doubly Link List
// Make a circular linked list of single node
// (or root). To do so, make the right and
// left pointers of this node point to itself
root.left = root.right = root;
// Step 1 (concatenate the left list with the list
// with single node, i.e., current node)
// Step 2 (concatenate the returned list with the
// right List)
return concatenate(concatenate(left, root), right);
}
// Display Circular Link List
public void display(Node head)
{
System.out.println("Circular Linked List is :");
Node itr = head;
do
{
System.out.print(itr.val+ " " );
itr = itr.right;
}
while (itr != head);
System.out.println();
}
}
// 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);
// head refers to the head of the Link List
Node head = tree.bTreeToCList(tree.root);
// Display the Circular LinkedList
tree.display(head);
}
}
197
Chapter 35. Convert a Binary Tree to a Circular Doubly Link List
Output:
Circular Linked List is :
25 12 30 10 36 15
Source
https://www.geeksforgeeks.org/convert-a-binary-tree-to-a-circular-doubly-link-list/
198
Chapter 36
Convert a given Binary Tree to
Doubly Linked List | Set 1
Convert a given Binary Tree to Doubly Linked List | Set 1 - GeeksforGeeks
Given a Binary Tree (Bt), convert it to a Doubly Linked List(DLL). The left and right
pointers in nodes are to be used as previous and next pointers respectively in converted
DLL. The order of nodes in DLL must be same as Inorder of the given Binary Tree. The
first node of Inorder traversal (left most node in BT) must be head node of the DLL.
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 C++ program for in-place conversion of Binary Tree to DLL
#include <stdio.h>
/* 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;
// Convert the left subtree and link to root
if (root->left != NULL)
{
// Convert the left subtree
node* left = bintree2listUtil(root->left);
// Find inorder predecessor. After this loop, left
// will point to the inorder predecessor
for (; left->right!=NULL; left=left->right);
// Make root as next of the predecessor
left->right = root;
// Make predecssor as previous of root
root->left = left;
}
200
Chapter 36. Convert a given Binary Tree to Doubly Linked List | Set 1
// Convert the right subtree and link to root
if (root->right!=NULL)
{
// Convert the right subtree
node* right = bintree2listUtil(root->right);
// Find inorder successor. After this loop, right
// will point to the inorder successor
for (; right->left!=NULL; right = right->left);
// Make root as previous of successor
right->left = root;
// Make successor as next of root
root->right = right;
}
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;
// Convert to DLL using bintree2listUtil()
root = bintree2listUtil(root);
// bintree2listUtil() returns root node of the converted
// DLL. We need pointer to the leftmost node which is
// head of the constructed DLL, so move to the leftmost node
while (root->left != NULL)
root = root->left;
return (root);
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
node* newNode(int data)
{
node* new_node = new node;
new_node->data = data;
new_node->left = new_node->right = NULL;
return (new_node);
201
Chapter 36. Convert a given Binary Tree to Doubly Linked List | Set 1
/* Function to print nodes in a given doubly linked list */
void printList(node *node)
{
while (node!=NULL)
{
printf("%d ", node->data);
node = node->right;
}
}
/* Driver program to test above functions*/
int main()
{
// Let us create the tree shown in above diagram
node *root = newNode(10);
root->left = newNode(12);
root->right = newNode(15);
root->left->left = newNode(25);
root->left->right = newNode(30);
root->right->left = newNode(36);
// Convert to DLL
node *head = bintree2list(root);
// Print the converted list
printList(head);
return 0;
}
Java
// Java program to convert binary tree to double linked list
/* 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 */
Node bintree2listUtil(Node node)
{
// Base case
if (node == null)
return node;
// Convert the left subtree and link to root
if (node.left != null)
{
// Convert the left subtree
Node left = bintree2listUtil(node.left);
// Find inorder predecessor. After this loop, left
// will point to the inorder predecessor
for (; left.right != null; left = left.right);
// Make root as next of the predecessor
left.right = node;
// Make predecssor as previous of root
node.left = left;
}
// Convert the right subtree and link to root
if (node.right != null)
{
// Convert the right subtree
Node right = bintree2listUtil(node.right);
// Find inorder successor. After this loop, right
// will point to the inorder successor
for (; right.left != null; right = right.left);
// Make root as previous of successor
right.left = node;
// Make successor as next of root
node.right = right;
}
return node;
203
Chapter 36. Convert a given Binary Tree to Doubly Linked List | Set 1
// The main function that first calls bintree2listUtil(), then follows
// step 3 of the above algorithm
Node bintree2list(Node node)
{
// Base case
if (node == null)
return node;
// Convert to DLL using bintree2listUtil()
node = bintree2listUtil(node);
// bintree2listUtil() returns root node of the converted
// DLL. We need pointer to the leftmost node which is
// head of the constructed DLL, so move to the leftmost node
while (node.left != null)
node = node.left;
return node;
}
/* Function to print nodes in a given doubly linked list */
void printList(Node node)
{
while (node != null)
{
System.out.print(node.data + " ");
node = node.right;
}
}
/* Driver program to test above functions*/
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
// Let us create the tree shown in above diagram
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);
// Convert to DLL
Node head = tree.bintree2list(tree.root);
204
Chapter 36. Convert a given Binary Tree to Doubly Linked List | Set 1
// Print the converted list
tree.printList(head);
}
}
Python
# Python program to convert
# binary tree to doubly linked list
class Node(object):
"""Binary tree Node class has
data, left and right child"""
def __init__(self, item):
self.data = item
self.left = None
self.right = None
def BTToDLLUtil(root):
"""This is a utility function to
convert the binary tree to doubly
linked list. Most of the core task
is done by this function."""
if root is None:
return root
# Convert left subtree
# and link to root
if root.left:
# Convert the left subtree
left = BTToDLLUtil(root.left)
# Find inorder predecessor, After
# this loop, left will point to the
# inorder predecessor of root
while left.right:
left = left.right
# Make root as next of predecessor
left.right = root
# Make predecessor as
# previous of root
root.left = left
205
Chapter 36. Convert a given Binary Tree to Doubly Linked List | Set 1
# Convert the right subtree
# and link to root
if root.right:
# Convert the right subtree
right = BTToDLLUtil(root.right)
# Find inorder successor, After
# this loop, right will point to
# the inorder successor of root
while right.left:
right = right.left
# Make root as previous
# of successor
right.left = root
# Make successor as
# next of root
root.right = right
return root
def BTToDLL(root):
if root is None:
return root
# Convert to doubly linked
# list using BLLToDLLUtil
root = BTToDLLUtil(root)
# We need pointer to left most
# node which is head of the
# constructed Doubly Linked list
while root.left:
root = root.left
return root
def print_list(head):
"""Function to print the given
doubly linked list"""
if head is None:
return
while head:
print(head.data, end = " ")
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)
# This code is contributed
# by viveksyngh
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
Convert a given Binary Tree to
Doubly Linked List | Set 2
Convert a given Binary Tree to Doubly Linked List | Set 2 - GeeksforGeeks
Given a Binary Tree (BT), convert it to a Doubly Linked List(DLL). The left and right
pointers in nodes are to be used as previous and next pointers respectively in converted
DLL. The order of nodes in DLL must be same as Inorder of the given Binary Tree. The
first node of Inorder traversal (left most node in BT) must be head node of the DLL.
A solution to this problem is discussed in this post.
In this post, another simple and efficient solution is discussed. The solution discussed here
has two simple steps.
1) Fix Left Pointers: In this step, we change left pointers to point to previous nodes in
DLL. The idea is simple, we do inorder traversal of tree. In inorder traversal, we keep track
of previous visited node and change left pointer to the previous node. See fixPrevPtr() in
below implementation.
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 simple inorder traversal based program to convert a Binary Tree to DLL
#include<stdio.h>
#include<stdlib.h>
// A tree node
struct node
{
int data;
struct node *left, *right;
};
// A utility function to create a new tree node
struct node *newNode(int data)
{
struct node *node = (struct node *)malloc(sizeof(struct node));
node->data = data;
node->left = node->right = NULL;
return(node);
}
// Standard Inorder traversal of tree
void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("\t%d",root->data);
inorder(root->right);
}
}
// Changes left pointers to work as previous pointers in converted DLL
// The function simply does inorder traversal of Binary Tree and updates
// left pointer using previously visited node
void fixPrevPtr(struct node *root)
{
static struct node *pre = NULL;
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);
}
}
// Changes right pointers to work as next pointers in converted DLL
struct node *fixNextPtr(struct node *root)
{
struct node *prev = NULL;
// Find the right most node in BT or last node in DLL
while (root && root->right != NULL)
root = 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 leftmost node is head of linked list, return it
return (root);
}
// 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);
// Set the next pointer and return head of DLL
return fixNextPtr(root);
}
// Traverses the DLL from left tor right
void printList(struct node *root)
{
while (root != NULL)
{
printf("\t%d", root->data);
root = root->right;
}
210
Chapter 37. Convert a given Binary Tree to Doubly Linked List | Set 2
// Driver program to test above functions
int main(void)
{
// Let us create the tree shown in above diagram
struct node *root = newNode(10);
root->left = newNode(12);
root->right = newNode(15);
root->left->left = newNode(25);
root->left->right = newNode(30);
root->right->left = newNode(36);
printf("\n\t\tInorder Tree Traversal\n\n");
inorder(root);
struct node *head = BTToDLL(root);
printf("\n\n\t\tDLL Traversal\n\n");
printList(head);
return 0;
}
Java
// Java program to convert BTT to DLL using
// simple inorder traversal
public class BinaryTreeToDLL
{
static class node
{
int data;
node left, right;
public node(int data)
{
this.data = data;
}
}
static node prev;
// Changes left pointers to work as previous
// pointers in converted DLL The function
// simply does inorder traversal of Binary
// Tree and updates left pointer using
// previously visited node
211
Chapter 37. Convert a given Binary Tree to Doubly Linked List | Set 2
static void fixPrevptr(node root)
{
if (root == null)
return;
fixPrevptr(root.left);
root.left = prev;
prev = root;
fixPrevptr(root.right);
// Changes right pointers to work
// as next pointers in converted DLL
static node fixNextptr(node root)
{
// Find the right most node in
// BT or last node in DLL
while (root.right != null)
root = root.right;
// Start from the rightmost node, traverse
// back using left pointers. While traversing,
// change right pointer of nodes
while (root != null && root.left != null)
{
node left = root.left;
left.right = root;
root = root.left;
}
// The leftmost node is head of linked list, return it
return root;
}
static node BTTtoDLL(node root)
{
prev = null;
// Set the previous pointer
fixPrevptr(root);
// Set the next pointer and return head of DLL
return fixNextptr(root);
}
// Traverses the DLL from left tor right
static void printlist(node root)
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;
}
}
// Standard Inorder traversal of tree
static void inorder(node root)
{
if (root == null)
return;
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}
public static void main(String[] args)
{
// Let us create the tree shown in above diagram
node root = new node(10);
root.left = new node(12);
root.right = new node(15);
root.left.left = new node(25);
root.left.right = new node(30);
root.right.left = new node(36);
System.out.println("Inorder Tree Traversal");
inorder(root);
node head = BTTtoDLL(root);
System.out.println("\nDLL Traversal");
printlist(head);
}
}
// This code is contributed by Rishabh Mahrsee
Python
# A simple inorder traversal based program to convert a
# Binary Tree to DLL
# A Binary Tree node
class Node:
213
Chapter 37. Convert a given Binary Tree to Doubly Linked List | Set 2
# Constructor to create a new tree node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Standard Inorder traversal of tree
def inorder(root):
if root is not None:
inorder(root.left)
print "\t%d" %(root.data),
inorder(root.right)
# Changes left pointers to work as previous pointers
# in converted DLL
# The function simply does inorder traversal of
# Binary Tree and updates
# left pointer using previously visited node
def fixPrevPtr(root):
if root is not None:
fixPrevPtr(root.left)
root.left = fixPrevPtr.pre
fixPrevPtr.pre = root
fixPrevPtr(root.right)
# Changes right pointers to work as nexr pointers in
# converted DLL
def fixNextPtr(root):
prev = None
# Find the right most node in BT or last node in DLL
while(root and root.right != None):
root = root.right
# Start from the rightmost node, traverse back using
# left pointers
# While traversing, change right pointer of nodes
while(root and root.left != None):
prev = root
root = root.left
root.right = prev
# The leftmost node is head of linked list, return it
return root
# The main function that converts BST to DLL and returns
# head of DLL
214
Chapter 37. Convert a given Binary Tree to Doubly Linked List | Set 2
def BTToDLL(root):
# Set the previous pointer
fixPrevPtr(root)
# Set the next pointer and return head of DLL
return fixNextPtr(root)
# Traversses the DLL from left to right
def printList(root):
while(root != None):
print "\t%d" %(root.data),
root = root.right
# Driver program to test above function
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)
print "\n\t\t Inorder Tree Traversal\n"
inorder(root)
# Static variable pre for function fixPrevPtr
fixPrevPtr.pre = None
head = BTToDLL(root)
print "\n\n\t\tDLL Traversal\n"
printList(head)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Inorder Tree Traversal
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
Convert a given Binary Tree to
Doubly Linked List | Set 3
Convert a given Binary Tree to Doubly Linked List | Set 3 - GeeksforGeeks
Given a Binary Tree (BT), convert it to a Doubly Linked List(DLL) In-Place. The left and
right pointers in nodes are to be used as previous and next pointers respectively in converted
DLL. The order of nodes in DLL must be same as Inorder of the given Binary Tree. The
first node of Inorder traversal (left most node in BT) must be head node of the DLL.
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 C++ program for in-place conversion of Binary Tree to DLL
#include <iostream>
using namespace std;
/* A binary tree node has data, and left and right pointers */
struct node
{
int data;
node* left;
node* right;
};
// A simple recursive function to convert a given Binary tree to Doubly
// Linked List
// root --> Root of Binary Tree
// head --> Pointer to head node of created doubly linked list
void BinaryTree2DoubleLinkedList(node *root, node **head)
{
// Base case
if (root == NULL) return;
// Initialize previously visited node as NULL. This is
// static so that the same value is accessible in all recursive
// calls
static node* prev = NULL;
// Recursively convert left subtree
BinaryTree2DoubleLinkedList(root->left, head);
// Now convert this node
if (prev == NULL)
*head = root;
else
{
root->left = prev;
prev->right = root;
}
prev = root;
// Finally convert right subtree
BinaryTree2DoubleLinkedList(root->right, head);
218
Chapter 38. Convert a given Binary Tree to Doubly Linked List | Set 3
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
node* newNode(int data)
{
node* new_node = new node;
new_node->data = data;
new_node->left = new_node->right = NULL;
return (new_node);
}
/* Function to print nodes in a given doubly linked list */
void printList(node *node)
{
while (node!=NULL)
{
cout << node->data << " ";
node = node->right;
}
}
/* Driver program to test above functions*/
int main()
{
// Let us create the tree shown in above diagram
node *root = newNode(10);
root->left = newNode(12);
root->right = newNode(15);
root->left->left = newNode(25);
root->left->right = newNode(30);
root->right->left = newNode(36);
// Convert to DLL
node *head = NULL;
BinaryTree2DoubleLinkedList(root, &head);
// Print the converted list
printList(head);
return 0;
}
Java
// A Java program for in-place conversion of Binary Tree to DLL
// 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;
public Node(int data)
{
this.data = data;
left = right = null;
}
}
class BinaryTree
{
Node root;
// head --> Pointer to head node of created doubly linked list
Node head;
// Initialize previously visited node as NULL. This is
// static so that the same value is accessible in all recursive
// calls
static Node prev = null;
// A simple recursive function to convert a given Binary tree
// to Doubly Linked List
// root --> Root of Binary Tree
void BinaryTree2DoubleLinkedList(Node root)
{
// Base case
if (root == null)
return;
// Recursively convert left subtree
BinaryTree2DoubleLinkedList(root.left);
// Now convert this node
if (prev == null)
head = root;
else
{
root.left = prev;
prev.right = root;
}
prev = root;
// Finally convert right subtree
BinaryTree2DoubleLinkedList(root.right);
220
Chapter 38. Convert a given Binary Tree to Doubly Linked List | Set 3
/* Function to print nodes in a given doubly linked list */
void printList(Node node)
{
while (node != null)
{
System.out.print(node.data + " ");
node = node.right;
}
}
// Driver program to test above functions
public static void main(String[] args)
{
// Let us create the tree as shown in above diagram
BinaryTree tree = new BinaryTree();
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);
// convert to DLL
tree.BinaryTree2DoubleLinkedList(tree.root);
// Print the converted List
tree.printList(tree.head);
}
}
// 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
Convert a given Binary Tree to
Doubly Linked List | Set 4
Convert a given Binary Tree to Doubly Linked List | Set 4 - GeeksforGeeks
Given a Binary Tree (BT), convert it to a Doubly Linked List(DLL) In-Place. The left and
right pointers in nodes are to be used as previous and next pointers respectively in converted
DLL. The order of nodes in DLL must be same as Inorder of the given Binary Tree. The
first node of Inorder traversal (left most node in BT) must be head node of the DLL.
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++
// C++ program to convert a given Binary
// Tree to Doubly Linked List
#include <stdio.h>
#include <stdlib.h>
// Structure for tree and linked list
struct Node
{
int data;
Node *left, *right;
};
// A simple recursive function to convert a given
// Binary tree to Doubly Linked List
// root --> Root of Binary Tree
// head_ref --> Pointer to head node of created
// doubly linked list
void BToDLL(Node* root, Node** head_ref)
{
// Base cases
if (root == NULL)
return;
// Recursively convert right subtree
BToDLL(root->right, head_ref);
// insert root into DLL
root->right = *head_ref;
// Change left pointer of previous head
if (*head_ref != NULL)
(*head_ref)->left = root;
// Change head of Doubly linked list
*head_ref = root;
// Recursively convert left subtree
BToDLL(root->left, head_ref);
}
// Utility function for allocating node for Binary
// Tree.
Node* newNode(int data)
{
224
Chapter 39. Convert a given Binary Tree to Doubly Linked List | Set 4
Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return node;
}
// Utility function for printing double linked list.
void printList(Node* head)
{
printf("Extracted Double Linked list is:\n");
while (head)
{
printf("%d ", head->data);
head = head->right;
}
}
// Driver program to test above function
int main()
{
/* Constructing below tree
5
/ \
3 6
/ \ \
1 4 8
/ \ / \
0 2 7 9 */
Node* root = newNode(5);
root->left = newNode(3);
root->right = newNode(6);
root->left->left = newNode(1);
root->left->right = newNode(4);
root->right->right = newNode(8);
root->left->left->left = newNode(0);
root->left->left->right = newNode(2);
root->right->right->left = newNode(7);
root->right->right->right = newNode(9);
Node* head = NULL;
BToDLL(root, &head);
printList(head);
return 0;
}
Java
225
Chapter 39. Convert a given Binary Tree to Doubly Linked List | Set 4
// Java program to convert a given Binary Tree to
// Doubly Linked List
/* Structure for tree and Linked List */
class Node
{
int data;
Node left, right;
public Node(int data)
{
this.data = data;
left = right = null;
}
}
class BinaryTree
{
// 'root' - root of binary tree
Node root;
// 'head' - reference to head node of created
//double linked list
Node head;
// A simple recursive function to convert a given
// Binary tree to Doubly Linked List
void BToDLL(Node root)
{
// Base cases
if (root == null)
return;
// Recursively convert right subtree
BToDLL(root.right);
// insert root into DLL
root.right = head;
// Change left pointer of previous head
if (head != null)
(head).left = root;
// Change head of Doubly linked list
head = root;
// Recursively convert left subtree
BToDLL(root.left);
226
Chapter 39. Convert a given Binary Tree to Doubly Linked List | Set 4
// Utility function for printing double linked list.
void printList(Node head)
{
System.out.println("Extracted Double Linked List is : ");
while (head != null)
{
System.out.print(head.data + " ");
head = head.right;
}
}
// Driver program to test the above functions
public static void main(String[] args)
{
/* Constructing below tree
5
/ \
3 6
/ \ \
1 4 8
/ \ / \
0 2 7 9 */
BinaryTree tree = new BinaryTree();
tree.root = new Node(5);
tree.root.left = new Node(3);
tree.root.right = new Node(6);
tree.root.left.right = new Node(4);
tree.root.left.left = new Node(1);
tree.root.right.right = new Node(8);
tree.root.left.left.right = new Node(2);
tree.root.left.left.left = new Node(0);
tree.root.right.right.left = new Node(7);
tree.root.right.right.right = new Node(9);
tree.BToDLL(tree.root);
tree.printList(tree.head);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Output :
Extracted Double Linked list is:
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
Convert singly linked list into
circular linked list
Convert singly linked list into circular linked list - GeeksforGeeks
Given a singly linked list, we have to convert it into circular linked list. For example, we
have been given a singly linked list with four nodes and we want to convert this singly linked
list into circular linked list.
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.
// Program for converting singly linked list
// into circular linked list.
#include <bits/stdc++.h>
/* Linked list node */
struct Node {
int data;
struct Node* next;
};
229
Chapter 40. Convert singly linked list into circular linked list
// Function that convert singly linked list
// into circular linked list.
struct Node* circular(struct Node* head)
{
// declare a node variable start and
// assign head node into start node.
struct Node* start = head;
// check that while head->next not equal
// to NULL then head points to next node.
while (head->next != NULL)
head = head->next;
// if head->next points to NULL then
// start assign to the head->next node.
head->next = start;
return start;
}
void push(struct Node** head, int data)
{
// Allocate dynamic memory for newNode.
struct Node* newNode = (struct Node*)malloc
(sizeof(struct Node));
// Assign the data into newNode.
newNode->data = data;
// newNode->next assign the address of
// head node.
newNode->next = (*head);
// newNode become the headNode.
(*head) = newNode;
}
// Function that display the elements of
// circular linked list.
void displayList(struct Node* node)
{
struct Node* start = node;
while (node->next != start) {
printf("%d ", node->data);
node = node->next;
}
230
Chapter 40. Convert singly linked list into circular linked list
// Display the last node of circular
// linked list.
printf("%d ", node->data);
}
// Drier program to test the functions
int main()
{
// Start with empty list
struct Node* head = NULL;
// Using push() function to construct
// singly linked list
// 17->22->13->14->15
push(&head, 15);
push(&head, 14);
push(&head, 13);
push(&head, 22);
push(&head, 17);
// Call the circular_list function that
// convert singly linked list to circular
// linked list.
circular(head);
printf("Display list: \n");
displayList(head);
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
Count nodes in Circular linked
list
Count nodes in Circular linked list - GeeksforGeeks
Given a circular linked list, count number of nodes in it. For example output is 5 for below
list.
We use the concept used inCircular Linked List | Set 2 (Traversal). While traversing, we
keep track of count of nodes.
// C program to count number of nodes in
// a circular linked list.
#include <stdio.h>
#include <stdlib.h>
/* structure for a node */
struct Node {
int data;
struct Node* next;
};
/* Function to insert a node at the begining
of a Circular linked list */
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;
232
Chapter 41. Count nodes in Circular linked list
ptr1->next = *head_ref;
/* 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;
}
/* Function to print nodes in a given Circular
linked list */
int countNodes(struct Node* head)
{
struct Node* temp = head;
int result = 0;
if (head != NULL) {
do {
temp = temp->next;
result++;
} while (temp != head);
}
return result;
}
/* Driver program to test above functions */
int main()
{
/* Initialize lists as empty */
struct Node* head = NULL;
push(&head, 12);
push(&head, 56);
push(&head, 2);
push(&head, 11);
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
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:
Input : list1 = 3->1->5->7
list2 = 8->2->5->3
x = 10
Output : 2
The pairs are:
(5, 5) and (7, 3)
Input : list1 = 4->3->5->7->11->2->1
list2 = 2->3->4->5->6->8-12
x = 9
Output : 5
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
// C++ implementation to count pairs from both linked
// lists whose sum is equal to a given value
#include <bits/stdc++.h>
using namespace std;
/* A Linked list node */
struct Node
{
int data;
struct Node* next;
};
// function to insert a node at the
// beginning 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));
/* put in the data */
new_node->data = new_data;
/* link the old list to the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
// function to count all pairs from both the linked lists
// whose sum is equal to a given value
int countPairs(struct Node* head1, struct Node* head2, int x)
{
int count = 0;
struct Node *p1, *p2;
// traverse the 1st linked list
for (p1 = head1; p1 != NULL; p1 = p1->next)
// for each node of 1st list
// traverse the 2nd list
for (p2 = head2; p2 != NULL; p2 = p2->next)
// if sum of pair is equal to 'x'
// increment count
236
Chapter 42. Count pairs from two linked lists whose sum is equal to a given value
if ((p1->data + p2->data) == x)
count++;
// required count of pairs
return count;
}
// Driver program to test above
int main()
{
struct Node* head1 = NULL;
struct Node* head2 = NULL;
// create linked list1 3->1->5->7
push(&head1, 7);
push(&head1, 5);
push(&head1, 1);
push(&head1, 3);
// create linked list2 8->2->5->3
push(&head2, 3);
push(&head2, 5);
push(&head2, 2);
push(&head2, 8);
int x = 10;
cout << "Count = "
<< countPairs(head1, head2, x);
return 0;
}
Java
// Java implementation to count pairs from both linked
// lists whose sum is equal to a given value
// Note : here we use java.util.LinkedList for
// linked list implementation
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
static int countPairs(LinkedList<Integer> head1, LinkedList<Integer> head2, int x)
{
int count = 0;
// traverse the 1st linked list
Iterator<Integer> itr1 = head1.iterator();
while(itr1.hasNext())
{
// for each node of 1st list
// traverse the 2nd list
Iterator<Integer> itr2 = head2.iterator();
while(itr2.hasNext())
{
// if sum of pair is equal to 'x'
// increment count
if ((itr1.next() + itr2.next()) == x)
count++;
}
}
// required count of pairs
return count;
}
// Driver method
public static void main(String[] args)
{
Integer arr1[] = {3, 1, 5, 7};
Integer arr2[] = {8, 2, 5, 3};
// create linked list1 3->1->5->7
LinkedList<Integer> head1 = new LinkedList<>(Arrays.asList(arr1));
// create linked list2 8->2->5->3
LinkedList<Integer> head2 = new LinkedList<>(Arrays.asList(arr2));
int x = 10;
System.out.println("Count = " + countPairs(head1, head2, x));
}
}
Output:
Count = 2
238
Chapter 42. Count pairs from two linked lists whose sum is equal to a given value
Time Complexity: O(n1*n2)
Auxiliary Space: O(1)
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++
// C++ implementation to count pairs from both linked
// lists whose sum is equal to a given value
#include <bits/stdc++.h>
using namespace std;
/* A Linked list node */
struct Node
{
int data;
struct Node* next;
};
// function to insert a node at the
// beginning of the linked list
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
239
Chapter 42. Count pairs from two linked lists whose sum is equal to a given value
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list to the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
// function to count all pairs from both the linked
// lists whose sum is equal to a given value
int countPairs(struct Node* head1, struct Node* head2,
int x)
{
int count = 0;
// sort head1 in ascending order and
// head2 in descending order
// sort (head1), sort (head2)
// For simplicity both lists are considered to be
// sorted in the respective orders
// traverse both the lists from left to right
while (head1 != NULL && head2 != NULL)
{
// if this sum is equal to 'x', then move both
// the lists to next nodes and increment 'count'
if ((head1->data + head2->data) == x)
{
head1 = head1->next;
head2 = head2->next;
count++;
}
// if this sum is greater than x, then
// move head2 to next node
else if ((head1->data + head2->data) > x)
head2 = head2->next;
// else move head1 to next node
else
head1 = head1->next;
}
// required count of pairs
240
Chapter 42. Count pairs from two linked lists whose sum is equal to a given value
return count;
}
// Driver program to test above
int main()
{
struct Node* head1 = NULL;
struct Node* head2 = NULL;
// create linked list1 1->3->5->7
// assumed to be in ascending order
push(&head1, 7);
push(&head1, 5);
push(&head1, 3);
push(&head1, 1);
// create linked list2 8->5->3->2
// assumed to be in descending order
push(&head2, 2);
push(&head2, 3);
push(&head2, 5);
push(&head2, 8);
int x = 10;
cout << "Count = "
<< countPairs(head1, head2, x);
return 0;
}
Java
// Java implementation to count pairs from both linked
// lists whose sum is equal to a given value
// Note : here we use java.util.LinkedList for
// linked list implementation
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;
// sort head1 in ascending order and
// head2 in descending order
Collections.sort(head1);
Collections.sort(head2,Collections.reverseOrder());
// traverse both the lists from left to right
Iterator<Integer> itr1 = head1.iterator();
Iterator<Integer> itr2 = head2.iterator();
Integer num1 = itr1.hasNext() ? itr1.next() : null;
Integer num2 = itr2.hasNext() ? itr2.next() : null;
while(num1 != null && num2 != null)
{
// if this sum is equal to 'x', then move both
// the lists to next nodes and increment 'count'
if ((num1 + num2) == x)
{
num1 = itr1.hasNext() ? itr1.next() : null;
num2 = itr2.hasNext() ? itr2.next() : null;
count++;
}
// if this sum is greater than x, then
// move itr2 to next node
else if ((num1 + num2) > x)
num2 = itr2.hasNext() ? itr2.next() : null;
// else move itr1 to next node
else
num1 = itr1.hasNext() ? itr1.next() : null;
// required count of pairs
return 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
Integer arr2[] = {8, 2, 5, 3};
// create linked list1 3->1->5->7
LinkedList<Integer> head1 = new LinkedList<>(Arrays.asList(arr1));
// create linked list2 8->2->5->3
LinkedList<Integer> head2 = new LinkedList<>(Arrays.asList(arr2));
int x = 10;
System.out.println("Count = " + countPairs(head1, head2, x));
}
}
Output:
Count = 2
Time Complexity: O(n1*logn1) + O(n2*logn2)
Auxiliary Space: O(1)
Sorting will change the order of nodes. If order is important, then copy of the linked lists
can be created and used.
Method 3 (Hashing): Hash table is implemented using unordered_set in C++. We store
all first linked list elements in hash table. For elements of second linked list, we subtract
every element from x and check the result in hash table. If result is present, we increment
the count.
C++
// C++ implementation to count pairs from both linked
// lists whose sum is equal to a given value
#include <bits/stdc++.h>
using namespace std;
/* A Linked list node */
struct Node
{
int data;
struct Node* next;
};
// function to insert a node at the
// beginning of the linked list
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
243
Chapter 42. Count pairs from two linked lists whose sum is equal to a given value
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list to the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
// function to count all pairs from both the linked
// lists whose sum is equal to a given value
int countPairs(struct Node* head1, struct Node* head2,
int x)
{
int count = 0;
unordered_set<int> us;
// insert all the elements of 1st list
// in the hash table(unordered_set 'us')
while (head1 != NULL)
{
us.insert(head1->data);
// move to next node
head1 = head1->next;
}
// for each element of 2nd list
while (head2 != NULL)
{
// find (x - head2->data) in 'us'
if (us.find(x - head2->data) != us.end())
count++;
// move to next node
head2 = head2->next;
}
// required count of pairs
return count;
}
// Driver program to test above
int main()
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;
// create linked list1 3->1->5->7
push(&head1, 7);
push(&head1, 5);
push(&head1, 1);
push(&head1, 3);
// create linked list2 8->2->5->3
push(&head2, 3);
push(&head2, 5);
push(&head2, 2);
push(&head2, 8);
int x = 10;
cout << "Count = "
<< countPairs(head1, head2, x);
return 0;
}
Java
// Java implementation to count pairs from both linked
// lists whose sum is equal to a given value
// Note : here we use java.util.LinkedList for
// linked list implementation
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;
HashSet<Integer> us = new HashSet<Integer>();
// insert all the elements of 1st list
// in the hash table(unordered_set 'us')
245
Chapter 42. Count pairs from two linked lists whose sum is equal to a given value
Iterator<Integer> itr1 = head1.iterator();
while (itr1.hasNext())
{
us.add(itr1.next());
Iterator<Integer> itr2 = head2.iterator();
// for each element of 2nd list
while (itr2.hasNext())
{
// find (x - head2->data) in 'us'
if (us.add(x - itr2.next()))
count++;
// required count of pairs
return count;
}
// Driver method
public static void main(String[] args)
{
Integer arr1[] = {3, 1, 5, 7};
Integer arr2[] = {8, 2, 5, 3};
// create linked list1 3->1->5->7
LinkedList<Integer> head1 = new LinkedList<>(Arrays.asList(arr1));
// create linked list2 8->2->5->3
LinkedList<Integer> head2 = new LinkedList<>(Arrays.asList(arr2));
int x = 10;
System.out.println("Count = " + countPairs(head1, head2, x));
}
}
Output:
Count = 2
Time Complexity: O(n1 + n2)
Auxiliary Space: O(n1), hash table should be created of the array having smaller size so as
to reduce the space complexity.
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
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.
// C++ implementation to count pairs in a binary tree
248
Chapter 43. Count pairs in a binary tree whose sum is equal to a given value x
// whose sum is equal to given value x
#include <bits/stdc++.h>
using namespace std;
// structure of a node of a binary tree
struct Node {
int data;
Node *left, *right;
};
// function to create and return a node
// of a binary tree
Node* getNode(int data)
{
// allocate space for the node
Node* new_node = (Node*)malloc(sizeof(Node));
// put in the data
new_node->data = data;
new_node->left = new_node->right = NULL;
}
// returns true if a pair exists with given sum 'x'
bool findPair(Node* root, Node* temp, int x)
{
// base case
if (!root)
return false;
// pair exists
if (root != temp && ((root->data + temp->data) == x))
return true;
// find pair in left and right subtress
if (findPair(root->left, temp, x) || findPair(root->right, temp, x))
return true;
// pair does not exists with given sum 'x'
return false;
}
// function to count pairs in a binary tree
// whose sum is equal to given value x
void countPairs(Node* root, Node* curr, int x, int& count)
{
// if tree is empty
if (!curr)
return;
249
Chapter 43. Count pairs in a binary tree whose sum is equal to a given value x
// check whether pair exists for current node 'curr'
// in the binary tree that sum up to 'x'
if (findPair(root, curr, x))
count++;
// recursively count pairs in left subtree
countPairs(root, curr->left, x, count);
// recursively count pairs in right subtree
countPairs(root, curr->right, x, count);
}
// Driver program to test above
int main()
{
// formation of binary tree
Node* root = getNode(5); /* 5 */
root->left = getNode(3); /* / \ */
root->right = getNode(7); /* 3 7 */
root->left->left = getNode(2); /* / \ / \ */
root->left->right = getNode(4); /* 2 4 6 8 */
root->right->left = getNode(6);
root->right->right = getNode(8);
int x = 10;
int count = 0;
countPairs(root, root, x, count);
count = count / 2;
cout << "Count = " << count;
return 0;
}
Output:
Count = 3
Time Complexity: O(n^2).
Efficient Approach: Following are the steps:
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
4. Display the count obtained in Step 4.
// C++ implementation to count pairs in a binary tree
// whose sum is equal to given value x
#include <bits/stdc++.h>
using namespace std;
// structure of a node of a binary tree
struct Node {
int data;
Node *left, *right;
};
// function to create and return a node
// of a binary tree
Node* getNode(int data)
{
// allocate space for the node
Node* new_node = (Node*)malloc(sizeof(Node));
// put in the data
new_node->data = data;
new_node->left = new_node->right = NULL;
}
// A simple recursive function to convert a given
// Binary tree to Doubly Linked List
// root --> Root of Binary Tree
// head_ref --> Pointer to head node of created
// doubly linked list
void BToDLL(Node* root, Node** head_ref)
{
// Base cases
if (root == NULL)
return;
// Recursively convert right subtree
BToDLL(root->right, head_ref);
// insert root into DLL
root->right = *head_ref;
// Change left pointer of previous head
if (*head_ref != NULL)
(*head_ref)->left = root;
// Change head of Doubly linked list
*head_ref = root;
251
Chapter 43. Count pairs in a binary tree whose sum is equal to a given value x
// Recursively convert left subtree
BToDLL(root->left, head_ref);
}
// Split a doubly linked list (DLL) into 2 DLLs of
// half sizes
Node* split(Node* head)
{
Node *fast = head, *slow = head;
while (fast->right && fast->right->right) {
fast = fast->right->right;
slow = slow->right;
}
Node* temp = slow->right;
slow->right = NULL;
return temp;
}
// Function to merge two sorted doubly linked lists
Node* merge(Node* first, Node* second)
{
// If first linked list is empty
if (!first)
return second;
// If second linked list is empty
if (!second)
return first;
// Pick the smaller value
if (first->data < second->data) {
first->right = merge(first->right, second);
first->right->left = first;
first->left = NULL;
return first;
}
else {
second->right = merge(first, second->right);
second->right->left = second;
second->left = NULL;
return second;
}
}
// Function to do merge sort
Node* mergeSort(Node* head)
{
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);
// Recur for left and right halves
head = mergeSort(head);
second = mergeSort(second);
// Merge the two sorted halves
return merge(head, second);
}
// Function to count pairs in a sorted doubly linked list
// whose sum equal to given value x
int pairSum(Node* head, int x)
{
// Set two pointers, first to the beginning of DLL
// and second to the end of DLL.
Node* first = head;
Node* second = head;
while (second->right != NULL)
second = second->right;
int count = 0;
// The loop terminates when either of two pointers
// become NULL, or they cross each other (second->right
// == first), or they become same (first == second)
while (first != NULL && second != NULL && first != second && second->right != first) {
// pair found
if ((first->data + second->data) == x) {
count++;
// move first in forward direction
first = first->right;
// move second in backward direction
second = second->left;
}
else {
if ((first->data + second->data) < x)
first = first->right;
else
second = second->left;
}
}
return count;
253
Chapter 43. Count pairs in a binary tree whose sum is equal to a given value x
// function to count pairs in a binary tree
// whose sum is equal to given value x
int countPairs(Node* root, int x)
{
Node* head = NULL;
int count = 0;
// Convert binary tree to
// doubly linked list
BToDLL(root, &head);
// sort DLL
head = mergeSort(head);
// count pairs
return pairSum(head, x);
}
// Driver program to test above
int main()
{
// formation of binary tree
Node* root = getNode(5); /* 5 */
root->left = getNode(3); /* / \ */
root->right = getNode(7); /* 3 7 */
root->left->left = getNode(2); /* / \ / \ */
root->left->right = getNode(4); /* 2 4 6 8 */
root->right->left = getNode(6);
root->right->right = getNode(8);
int x = 10;
cout << "Count = "
<< countPairs(root, x);
return 0;
}
Output:
Count = 3
Time Complexity: O(nLog n).
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
Count rotations in sorted and
rotated linked list
Count rotations in sorted and rotated linked list - GeeksforGeeks
Given a linked list of n nodes which is first sorted, then rotated by k elements. Find the
value of k.
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.
// Program for count number of rotations in
// sorted linked list.
#include <bits/stdc++.h>
using namespace std;
/* Linked list node */
struct Node {
int data;
struct Node* next;
};
256
Chapter 44. Count rotations in sorted and rotated linked list
// Function that count number of
// rotation in singly linked list.
int countRotation(struct Node* head)
{
// declare count variable and assign it 1.
int count = 0;
// declare a min variable and assign to
// data of head node.
int min = head->data;
// check that while head not equal to NULL.
while (head != NULL) {
// if min value is greater then head->data
// then it breaks the while loop and
// return the value of count.
if (min > head->data)
break;
count++;
// head assign the next value of head.
head = head->next;
}
return count;
}
// Function to push element in linked list.
void push(struct Node** head, int data)
{
// Allocate dynamic memory for newNode.
struct Node* newNode = new Node;
// Assign the data into newNode.
newNode->data = data;
// newNode->next assign the address of
// head node.
newNode->next = (*head);
// newNode become the headNode.
(*head) = newNode;
}
// Display linked list.
void printList(struct Node* node)
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;
// push() insert node in linked list.
// 15 -> 18 -> 5 -> 8 -> 11 -> 12
push(&head, 12);
push(&head, 11);
push(&head, 8);
push(&head, 5);
push(&head, 18);
push(&head, 15);
printList(head);
cout << endl;
cout << "Linked list rotated elements: ";
// Function call countRotation()
cout << countRotation(head) << endl;
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
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:
Method 1 (Naive Approach):
Using three nested loops generate all triplets and check whether elements in the triplet sum
up to x or not.
// C++ implementation to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
#include <bits/stdc++.h>
using namespace std;
259
Chapter 45. Count triplets in a sorted doubly linked list whose sum is equal to a given
value x
// structure of node of doubly linked list
struct Node {
int data;
struct Node* next, *prev;
};
// function to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
int countTriplets(struct Node* head, int x)
{
struct Node* ptr1, *ptr2, *ptr3;
int count = 0;
// generate all possible triplets
for (ptr1 = head; ptr1 != NULL; ptr1 = ptr1->next)
for (ptr2 = ptr1->next; ptr2 != NULL; ptr2 = ptr2->next)
for (ptr3 = ptr2->next; ptr3 != NULL; ptr3 = ptr3->next)
// if elements in the current triplet sum up to 'x'
if ((ptr1->data + ptr2->data + ptr3->data) == x)
// increment count
count++;
// required count of triplets
return count;
}
// A utility function to insert a new node at the
// beginning of doubly linked list
void insert(struct Node** head, int data)
{
// allocate node
struct Node* temp = new Node();
// put in the data
temp->data = data;
temp->next = temp->prev = NULL;
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
// Driver program to test above
int main()
{
// start with an empty doubly linked list
struct Node* head = NULL;
// insert values in sorted order
insert(&head, 9);
insert(&head, 8);
insert(&head, 6);
insert(&head, 5);
insert(&head, 4);
insert(&head, 2);
insert(&head, 1);
int x = 17;
cout << "Count = "
<< countTriplets(head, x);
return 0;
}
Output:
Count = 2
Time Complexity: O(n3 )
Auxiliary Space: O(1)
Method 2 (Hashing):
Create a hash table with (key, value) tuples represented as (node data, node pointer)
tuples. Traverse the doubly linked list and store each node’s data and its pointer pair(tuple)
in the hash table. Now, generate each possible pair of nodes. For each pair of nodes, calculate
the p_sum(sum of data in the two nodes) and check whether (x-p_sum) exists in the
hash table or not. If it exists, then also verify that the two nodes in the pair are not same
to the node associated with (x-p_sum) in the hash table and finally increment count.
Return (count / 3) as each triplet is counted 3 times in the above process.
// C++ implementation to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
#include <bits/stdc++.h>
using namespace std;
// structure of node of doubly linked list
struct Node {
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;
};
// function to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
int countTriplets(struct Node* head, int x)
{
struct Node* ptr, *ptr1, *ptr2;
int count = 0;
// unordered_map 'um' implemented as hash table
unordered_map<int, Node*> um;
// insert the <node data, node pointer> tuple in 'um'
for (ptr = head; ptr != NULL; ptr = ptr->next)
um[ptr->data] = ptr;
// generate all possible pairs
for (ptr1 = head; ptr1 != NULL; ptr1 = ptr1->next)
for (ptr2 = ptr1->next; ptr2 != NULL; ptr2 = ptr2->next) {
// p_sum - sum of elements in the current pair
int p_sum = ptr1->data + ptr2->data;
// if 'x-p_sum' is present in 'um' and either of the two nodes
// are not equal to the 'um[x-p_sum]' node
if (um.find(x - p_sum) != um.end() && um[x - p_sum] != ptr1
&& um[x - p_sum] != ptr2)
// increment count
count++;
}
// required count of triplets
// division by 3 as each triplet is counted 3 times
return (count / 3);
}
// A utility function to insert a new node at the
// beginning of doubly linked list
void insert(struct Node** head, int data)
{
// allocate node
struct Node* temp = new Node();
// put in the data
temp->data = data;
262
Chapter 45. Count triplets in a sorted doubly linked list whose sum is equal to a given
value x
temp->next = temp->prev = NULL;
if ((*head) == NULL)
(*head) = temp;
else {
temp->next = *head;
(*head)->prev = temp;
(*head) = temp;
}
}
// Driver program to test above
int main()
{
// start with an empty doubly linked list
struct Node* head = NULL;
// insert values in sorted order
insert(&head, 9);
insert(&head, 8);
insert(&head, 6);
insert(&head, 5);
insert(&head, 4);
insert(&head, 2);
insert(&head, 1);
int x = 17;
cout << "Count = "
<< countTriplets(head, x);
return 0;
}
Output:
Count = 2
Time Complexity: O(n2 )
Auxiliary Space: O(n)
Method 3 Efficient Approach(Use of two pointers):
Traverse the doubly linked list from left to right. For each current node during the traversal,
initailze two pointers first = pointer to the node next to the current node and last =
pointer to the last node of the list. Now, count pairs in the list from first to last pointer
that sum up to value (x – current node’s data) (algorithm described in this post). Add
this count to the total_count of triplets. Pointer to the last node can be found only once
in the beginning.
263
Chapter 45. Count triplets in a sorted doubly linked list whose sum is equal to a given
value x
// C++ implementation to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
#include <bits/stdc++.h>
using namespace std;
// structure of node of doubly linked list
struct Node {
int data;
struct Node* next, *prev;
};
// function to count pairs whose sum equal to given 'value'
int countPairs(struct Node* first, struct Node* second, int value)
{
int count = 0;
// The loop terminates when either of two pointers
// become NULL, or they cross each other (second->next
// == first), or they become same (first == second)
while (first != NULL && second != NULL &&
first != second && second->next != first) {
// pair found
if ((first->data + second->data) == value) {
// increment count
count++;
// move first in forward direction
first = first->next;
// move second in backward direction
second = second->prev;
}
// if sum is greater than 'value'
// move second in backward direction
else if ((first->data + second->data) > value)
second = second->prev;
// else move first in forward direction
else
first = first->next;
}
// required count of pairs
return count;
264
Chapter 45. Count triplets in a sorted doubly linked list whose sum is equal to a given
value x
// function to count triplets in a sorted doubly linked list
// whose sum is equal to a given value 'x'
int countTriplets(struct Node* head, int x)
{
// if list is empty
if (head == NULL)
return 0;
struct Node* current, *first, *last;
int count = 0;
// get pointer to the last node of
// the doubly linked list
last = head;
while (last->next != NULL)
last = last->next;
// traversing the doubly linked list
for (current = head; current != NULL; current = current->next) {
// for each current node
first = current->next;
// count pairs with sum(x - current->data) in the range
// first to last and add it to the 'count' of triplets
count += countPairs(first, last, x - current->data);
}
// required count of triplets
return count;
}
// A utility function to insert a new node at the
// beginning of doubly linked list
void insert(struct Node** head, int data)
{
// allocate node
struct Node* temp = new Node();
// put in the data
temp->data = data;
temp->next = temp->prev = NULL;
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;
}
}
// Driver program to test above
int main()
{
// start with an empty doubly linked list
struct Node* head = NULL;
// insert values in sorted order
insert(&head, 9);
insert(&head, 8);
insert(&head, 6);
insert(&head, 5);
insert(&head, 4);
insert(&head, 2);
insert(&head, 1);
int x = 17;
cout << "Count = "
<< countTriplets(head, x);
return 0;
}
Output:
Count = 2
Time Complexity: O(n2 )
Auxiliary Space: O(1)
Source
https://www.geeksforgeeks.org/count-triplets-sorted-doubly-linked-list-whose-sum-equal-given-value-x/
266
Chapter 46
Create a Doubly Linked List
from a Ternary Tree
Create a Doubly Linked List from a Ternary Tree - GeeksforGeeks
Given a ternary tree, create a doubly linked list out of it. A ternary tree is just like binary
tree but instead of having two nodes, it has three nodes i.e. left, middle, right.
The doubly linked list should holds following properties –
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++
// C++ program to create a doubly linked list out
// of given a ternary tree.
#include <bits/stdc++.h>
using namespace std;
/* A ternary tree */
struct Node
{
int data;
struct Node *left, *middle, *right;
};
/* Helper function that allocates a new node with the
given data and assign NULL to left, middle and right
pointers.*/
Node* newNode(int data)
{
Node* node = new Node;
268
Chapter 46. Create a Doubly Linked List from a Ternary Tree
node->data = data;
node->left = node->middle = node->right = NULL;
return node;
}
/* Utility function that constructs doubly linked list
by inserting current node at the end of the doubly
linked list by using a tail pointer */
void push(Node** tail_ref, Node* node)
{
// initilize tail pointer
if (*tail_ref == NULL)
{
*tail_ref = node;
// set left, middle and right child to point
// to NULL
node->left = node->middle = node->right = NULL;
return;
}
// insert node in the end using tail pointer
(*tail_ref)->right = node;
// set prev of node
node->left = (*tail_ref);
// set middle and right child to point to NULL
node->right = node->middle = NULL;
// now tail pointer will point to inserted node
(*tail_ref) = node;
}
/* Create a doubly linked list out of given a ternary tree.
by traversing the tree in preoder fashion. */
Node* TernaryTreeToList(Node* root, Node** head_ref)
{
// Base case
if (root == NULL)
return NULL;
//create a static tail pointer
static Node* tail = NULL;
// store left, middle and right nodes
// for future calls.
269
Chapter 46. Create a Doubly Linked List from a Ternary Tree
Node* left = root->left;
Node* middle = root->middle;
Node* right = root->right;
// set head of the doubly linked list
// head will be root of the ternary tree
if (*head_ref == NULL)
*head_ref = root;
// push current node in the end of DLL
push(&tail, root);
//recurse for left, middle and right child
TernaryTreeToList(left, head_ref);
TernaryTreeToList(middle, head_ref);
TernaryTreeToList(right, head_ref);
}
// Utility function for printing double linked list.
void printList(Node* head)
{
printf("Created Double Linked list is:\n");
while (head)
{
printf("%d ", head->data);
head = head->right;
}
}
// Driver program to test above functions
int main()
{
// Construting ternary tree as shown in above figure
Node* root = newNode(30);
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);
Node* head = NULL;
TernaryTreeToList(root, &head);
printList(head);
return 0;
}
Java
//Java program to create a doubly linked list
// from a given ternary tree.
//Custom node class.
class newNode
{
int data;
newNode left,middle,right;
public newNode(int data)
{
this.data = data;
left = middle = right = null;
}
}
class GFG {
//tail of the linked list.
static newNode tail;
//function to push the node to the tail.
public static void push(newNode node)
{
//to put the node at the end of
// the already existing tail.
tail.right = node;
//to point to the previous node.
node.left = tail;
// middle pointer should point to
// nothing so null. initiate right
// pointer to null.
node.middle = node.right = null;
271
Chapter 46. Create a Doubly Linked List from a Ternary Tree
//update the tail position.
tail = node;
}
/* Create a doubly linked list out of given a ternary tree.
by traversing the tree in preoder fashion. */
public static void ternaryTree(newNode node,newNode head)
{
if(node == null)
return;
newNode left = node.left;
newNode middle = node.middle;
newNode right = node.right;
if(tail != node)
// already root is in the tail so dont push
// the node when it was root.In the first
// case both node and tail have root in them.
push(node);
// First the left child is to be taken.
// Then middle and then right child.
ternaryTree(left,head);
ternaryTree(middle,head);
ternaryTree(right,head);
}
//function to initiate the list process.
public static newNode startTree(newNode root)
{
//Initiate the head and tail with root.
newNode head = root;
tail = root;
ternaryTree(root,head);
//since the head,root are passed
// with reference the changes in
// root will be reflected in head.
return head;
}
// Utility function for printing double linked list.
public static void printList(newNode head)
{
System.out.print("Created Double Linked list is:\n");
while(head != null)
{
272
Chapter 46. Create a Doubly Linked List from a Ternary Tree
System.out.print(head.data + " ");
head = head.right;
}
}
// Driver program to test above functions
public static void main(String args[])
{
// Construting ternary tree as shown
// in above figure
newNode root = new newNode(30);
root.left = new newNode(5);
root.middle = new newNode(11);
root.right = new newNode(63);
root.left.left = new newNode(1);
root.left.middle = new newNode(4);
root.left.right = new newNode(8);
root.middle.left = new newNode(6);
root.middle.middle = new newNode(7);
root.middle.right = new newNode(15);
root.right.left = new newNode(31);
root.right.middle = new newNode(55);
root.right.right = new newNode(65);
// The function which initiates the list
// process returns the head.
newNode head = startTree(root);
printList(head);
}
}
// This code is contributed by M.V.S.Surya Teja.
Output:
Created Double Linked list is:
30 5 1 4 8 11 6 7 15 63 31 55 65
Improved By : MvssTeja
Source
https://www.geeksforgeeks.org/create-doubly-linked-list-ternary-ree/
273
Chapter 47
Data Structure design to
perform required operations
Data Structure design to perform required operations - GeeksforGeeks
Design a data structure which can do following operations
1. add() in O(n)
2. getMinimum() in O(1)
3. deleteMinimum() in O(1)
Source :MakeMyTrip Interview.
1. Maintain a linkedlist with elements in increasing order.
2. Move head to next position in case of delete Min operation.
3. Return First element in case of get Min Operation.
// Java code for linked list to
// perform required operations
import java.util.*;
// 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;
}
// Function to add element
void addElement(int d)
{
Node tmp = new Node(d);
// If linked list is empty
if (start == null)
{
start = tmp;
return;
}
// If head itself is greater
if (d < start.data)
{
tmp.next = start;
start = tmp;
return;
}
// If need to insert somewhere in middle
Node prev = start;
Node ptr = start.next;
while (ptr != null)
{
if (d < ptr.data)
{
tmp.next = ptr;
prev.next = tmp;
return;
}
else
{
prev = ptr;
ptr = ptr.next;
}
275
Chapter 47. Data Structure design to perform required operations
}
prev.next = tmp;
}
// Function to get minimum
int getMin()
{
return start.data;
}
// Function to delete minimum
int delMin()
{
int min = start.data;
start = start.next;
return min;
}
// Function to print elements
void print()
{
Node ptr = start;
System.out.print("Elements: ");
while (ptr != null)
{
System.out.print(ptr.data + ", ");
ptr = ptr.next;
}
System.out.println("\n");
}
// 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();
System.out.println("Get Min: " + x.getMin());
System.out.println("Del Min: " + x.delMin());
x.print();
System.out.println("Min: " + x.getMin());
}
}
276
Chapter 47. Data Structure design to perform required operations
Output:
Elements: 5, 10, 15, 20,
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
Decimal Equivalent of Binary
Linked List
Decimal Equivalent of Binary Linked List - GeeksforGeeks
Given a singly linked list of 0s and 1s find its decimal equivalent.
Input : 0->0->0->1->1->0->0->1->0
Output : 50
Input : 1->0->0
Output : 4
Decimal Value of an empty linked list is considered as 0.
Initialize result as 0. Traverse the linked list and for each node, multiply the result by 2 and
add node’s data to it.
// C++ Program to find decimal value of
// binary linked list
#include<iostream>
using namespace std;
/* Link list Node */
struct Node
{
bool data;
struct Node* next;
};
/* Returns decimal value of binary linked list */
int decimalValue(struct Node *head)
278
Chapter 48. Decimal Equivalent of Binary Linked List
{
// Initialized result
int res = 0;
// Traverse linked list
while (head != NULL)
{
// Multiply result by 2 and add
// head's data
res = (res << 1) + head->data;
// Move next
head = head->next;
}
return res;
}
// Utility function to create a new node.
Node *newNode(bool data)
{
struct Node *temp = new Node;
temp->data = data;
temp->next = NULL;
return temp;
}
/* Drier program to test above function*/
int main()
{
/* Start with the empty list */
struct Node* head = newNode(1);
head->next = newNode(0);
head->next->next = newNode(1);
head->next->next->next = newNode(1);
cout << "Decimal value is "
<< decimalValue(head);
return 0;
}
Output :
Decimal value is 11
Source
https://www.geeksforgeeks.org/decimal-equivalent-of-binary-linked-list/
279
Chapter 49
Delete N nodes after M nodes
of a linked list
Delete N nodes after M nodes of a linked list - GeeksforGeeks
Given a linked list and two integers M and N. Traverse the linked list such that you retain
M nodes then delete next N nodes, continue the same till end of the linked list.
Difficulty Level: Rookie
Examples:
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
// C program to delete N nodes after M nodes of a linked list
#include <stdio.h>
#include <stdlib.h>
// A linked list node
struct Node
{
int data;
struct Node *next;
};
/* Function to insert a node at the beginning */
void push(struct Node ** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print linked list */
void printList(struct Node *head)
{
struct Node *temp = head;
while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
// 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;
// The main loop that traverses through the whole list
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;
// If we reached end of list, then return
if (curr == NULL)
return;
// Start from next node and delete N nodes
t = curr->next;
for (count = 1; count<=N && t!= NULL; count++)
{
struct node *temp = t;
t = t->next;
free(temp);
}
curr->next = t; // Link the previous list with remaining nodes
// Set current pointer for next iteration
curr = t;
}
}
// Driver program to test above functions
int main()
{
/* Create following linked list
1->2->3->4->5->6->7->8->9->10 */
struct Node* head = NULL;
int M=2, N=3;
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);
printf("M = %d, N = %d \nGiven Linked list is :\n", M, N);
printList(head);
skipMdeleteN(head, M, N);
282
Chapter 49. Delete N nodes after M nodes of a linked list
printf("\nLinked list after deletion is :\n");
printList(head);
return 0;
}
Python
# Python program to delete M nodes after N nodes
# Node class
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Utility function to prit the linked LinkedList
def printList(self):
temp = self.head
while(temp):
print temp.data,
temp = temp.next
def skipMdeleteN(self, M, N):
curr = self.head
# The main loop that traverses through the
# whole list
while(curr):
# Skip M nodes
for count in range(1, M):
if curr is None:
return
curr = curr.next
283
Chapter 49. Delete N nodes after M nodes of a linked list
if curr is None :
return
# Start from next node and delete N nodes
t = curr.next
for count in range(1, N+1):
if t is None:
break
t = t.next
# Link the previous list with reamining nodes
curr.next = t
# Set Current pointer for next iteration
curr = t
# Driver program to test above function
# Create following linked list
# 1->2->3->4->5->6->7->8->9->10
llist = LinkedList()
M = 2
N = 3
llist.push(10)
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)
print "M = %d, N = %d\nGiven Linked List is:" %(M, N)
llist.printList()
print
llist.skipMdeleteN(M, N)
print "\nLinked list after deletion is"
llist.printList()
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
M = 2, N = 3
284
Chapter 49. Delete N nodes after M nodes of a linked list
Given Linked list is :
1 2 3 4 5 6 7 8 9 10
Linked list after deletion is :
1 2 6 7
Time Complexity: O(n) where n is number of nodes in 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
Delete a Doubly Linked List
node at a given position
Delete a Doubly Linked List node at a given position - GeeksforGeeks
Given a doubly linked list and a position n. The task is to delete the node at the given
position n from the beginning.
Initial doubly linked list
Doubly Linked List after deletion of node at position n = 2
Approach: Following are the steps:
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.
/* C++ implementation to delete a doubly Linked List node
at the given position */
#include <bits/stdc++.h>
using namespace std;
286
Chapter 50. Delete a Doubly Linked List node at a given position
/* a node of the doubly linked list */
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
/* Function to delete a node in a Doubly Linked List.
head_ref --> pointer to head node pointer.
del --> pointer to node to be deleted. */
void deleteNode(struct Node** head_ref, struct Node* del)
{
/* base case */
if (*head_ref == NULL || del == NULL)
return;
/* If node to be deleted is head node */
if (*head_ref == del)
*head_ref = del->next;
/* Change next only if node to be deleted is NOT
the last node */
if (del->next != NULL)
del->next->prev = del->prev;
/* Change prev only if node to be deleted is NOT
the first node */
if (del->prev != NULL)
del->prev->next = del->next;
/* Finally, free the memory occupied by del*/
free(del);
}
/* Function to delete the node at the given position
in the doubly linked list */
void deleteNodeAtGivenPos(struct Node** head_ref, int n)
{
/* if list in NULL or invalid position is given */
if (*head_ref == NULL || n <= 0)
return;
struct Node* current = *head_ref;
int i;
/* traverse up to the node at position 'n' from
the beginning */
for (int i = 1; current != NULL && i < n; i++)
287
Chapter 50. Delete a Doubly Linked List node at a given position
current = current->next;
/* if 'n' is greater than the number of nodes
in the doubly linked list */
if (current == NULL)
return;
/* delete the node pointed to by 'current' */
deleteNode(head_ref, current);
}
/* 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));
/* put in the data */
new_node->data = new_data;
/* since we are adding at the beginning,
prev is always NULL */
new_node->prev = NULL;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* change prev of head node to new node */
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print nodes in a given doubly
linked list */
void printList(struct Node* head)
{
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
/* Driver program to test above functions*/
288
Chapter 50. Delete a Doubly Linked List node at a given position
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
/* Create the doubly linked list 10<->8<->4<->2<->5 */
push(&head, 5);
push(&head, 2);
push(&head, 4);
push(&head, 8);
push(&head, 10);
cout << "Doubly linked list before deletion:n";
printList(head);
int n = 2;
/* delete node at the given position 'n' */
deleteNodeAtGivenPos(&head, n);
cout << "\nDoubly linked list after deletion:n";
printList(head);
return 0;
}
Output:
Doubly linked list before deletion:
10 8 4 2 5
Doubly linked list after deletion:
10 4 2 5
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
Delete a Linked List node at a
given position
Delete a Linked List node at a given position - GeeksforGeeks
Given a singly linked list and a position, delete a linked list node at the given position.
Example:
Input: position = 1, Linked List = 8->2->3->1->7
Output: Linked List = 8->3->1->7
Input: position = 0, Linked List = 8->2->3->1->7
Output: Linked List = 2->3->1->7
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++
// A complete working C program to delete a node in a linked list
// at a given position
#include <stdio.h>
#include <stdlib.h>
// A linked list node
struct Node
{
int data;
struct Node *next;
290
Chapter 51. Delete a Linked List node at a given position
};
/* Given a reference (pointer to pointer) to the head of a list
and an int, inserts a new node on the front of the list. */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
/* Given a reference (pointer to pointer) to the head of a list
and a position, deletes the node at the given position */
void deleteNode(struct Node **head_ref, int position)
{
// If linked list is empty
if (*head_ref == NULL)
return;
// Store head node
struct Node* temp = *head_ref;
// If head needs to be removed
if (position == 0)
{
*head_ref = temp->next; // Change head
free(temp); // free old head
return;
}
// Find previous node of the node to be deleted
for (int i=0; temp!=NULL && i<position-1; i++)
temp = temp->next;
// If position is more than number of ndoes
if (temp == NULL || temp->next == NULL)
return;
// Node temp->next is the node to be deleted
// Store pointer to the next of node to be deleted
struct Node *next = temp->next->next;
// Unlink the node from linked list
free(temp->next); // Free memory
temp->next = next; // Unlink the deleted node from list
}
291
Chapter 51. Delete a Linked List node at a given position
// This function prints contents of linked list starting from
// the given node
void printList(struct Node *node)
{
while (node != NULL)
{
printf(" %d ", node->data);
node = node->next;
}
}
/* Drier program to test above functions*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
push(&head, 7);
push(&head, 1);
push(&head, 3);
push(&head, 2);
push(&head, 8);
puts("Created Linked List: ");
printList(head);
deleteNode(&head, 4);
puts("\nLinked List after Deletion at position 4: ");
printList(head);
return 0;
}
Java
// A complete working Java program to delete a node in a linked list
// at a given position
class LinkedList
{
Node head; // head of list
/* Linked list Node*/
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
292
Chapter 51. Delete a Linked List node at a given position
next = null;
}
}
/* Inserts a new Node at front of the list. */
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
/* Given a reference (pointer to pointer) to the head of a list
and a position, deletes the node at the given position */
void deleteNode(int position)
{
// If linked list is empty
if (head == null)
return;
// Store head node
Node temp = head;
// If head needs to be removed
if (position == 0)
{
head = temp.next; // Change head
return;
}
// Find previous node of the node to be deleted
for (int i=0; temp!=null && i<position-1; i++)
temp = temp.next;
// If position is more than number of ndoes
if (temp == null || temp.next == null)
return;
// Node temp->next is the node to be deleted
// Store pointer to the next of node to be deleted
Node next = temp.next.next;
293
Chapter 51. Delete a Linked List node at a given position
temp.next = next; // Unlink the deleted node from list
}
/* This function prints contents of linked list starting from
the given node */
public void printList()
{
Node tnode = head;
while (tnode != null)
{
System.out.print(tnode.data+" ");
tnode = tnode.next;
}
}
/* Drier program to test above functions. Ideally this function
should be in a separate user class. It is kept here to keep
code compact */
public static void main(String[] args)
{
/* Start with the empty list */
LinkedList llist = new LinkedList();
llist.push(7);
llist.push(1);
llist.push(3);
llist.push(2);
llist.push(8);
System.out.println("\nCreated Linked list is: ");
llist.printList();
llist.deleteNode(4); // Delete node at position 4
System.out.println("\nLinked List after Deletion at position 4: ");
llist.printList();
}
}
Python
# Python program to delete a node in a linked list
# at a given position
# Node class
class Node:
# Constructor to initialize the node object
294
Chapter 51. Delete a Linked List node at a given position
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Constructor to initialize head
def __init__(self):
self.head = None
# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Given a reference to the head of a list
# and a position, delete the node at a given position
def deleteNode(self, position):
# If linked list is empty
if self.head == None:
return
# Store head node
temp = self.head
# If head needs to be removed
if position == 0:
self.head = temp.next
temp = None
return
# Find previous node of the node to be deleted
for i in range(position -1 ):
temp = temp.next
if temp is None:
break
# If position is more than number of nodes
if temp is None:
return
if temp.next is None:
return
# Node temp.next is the node to be deleted
# store pointer to the next of node to be deleted
next = temp.next.next
295
Chapter 51. Delete a Linked List node at a given position
# Unlink the node from linked list
temp.next = None
temp.next = next
# Utility function to print the linked LinkedList
def printList(self):
temp = self.head
while(temp):
print " %d " %(temp.data),
temp = temp.next
# Driver program to test above function
llist = LinkedList()
llist.push(7)
llist.push(1)
llist.push(3)
llist.push(2)
llist.push(8)
print "Created Linked List: "
llist.printList()
llist.deleteNode(4)
print "\nLinked List after Deletion at position 4: "
llist.printList()
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Created Linked List:
8 2 3 1 7
Linked List after Deletion at position 4:
8 2 3 1
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
Delete a given node in Linked
List under given constraints
Delete a given node in Linked List under given constraints - GeeksforGeeks
Given a Singly Linked List, write a function to delete a given node. Your function must
follow following constraints:
1) It must accept pointer to the start node as first parameter and node to be deleted as
second parameter i.e., pointer to head node is not global.
2) It should not return pointer to the head node.
3) It should not accept pointer to pointer to head node.
You may assume that the Linked List never becomes empty.
Let the function name be deleteNode(). In a straightforward implementation, the function
needs to modify head pointer when the node to be deleted is first node. As discussed in
previous post, when a function modifies the head pointer, the function must use one of the
given approaches, we can’t use any of those approaches here.
Solution
We explicitly handle the case when node to be deleted is first node, we copy the data of
next node to head and delete the next node. The cases when deleted node is not the head
node can be handled normally by finding the previous node and changing next of previous
node. Following is C implementation.
C
#include <stdio.h>
#include <stdlib.h>
/* structure of a linked list node */
struct Node
{
int data;
struct Node *next;
297
Chapter 52. Delete a given node in Linked List under given constraints
};
void deleteNode(struct Node *head, struct Node *n)
{
// When node to be deleted is head node
if(head == n)
{
if(head->next == NULL)
{
printf("There is only one node. The list can't be made empty ");
return;
}
/* Copy the data of next node to head */
head->data = head->next->data;
// store address of next node
n = head->next;
// Remove the link of next node
head->next = head->next->next;
// free memory
free(n);
return;
}
// When not first node, follow the normal deletion process
// find the previous node
struct Node *prev = head;
while(prev->next != NULL && prev->next != n)
prev = prev->next;
// Check if node really exists in Linked List
if(prev->next == NULL)
{
printf("\n Given node is not present in Linked List");
return;
}
// Remove node from Linked List
prev->next = prev->next->next;
// Free memory
free(n);
298
Chapter 52. Delete a given node in Linked List under given constraints
return;
}
/* Utility function to insert a node at the begining */
void push(struct Node **head_ref, int new_data)
{
struct Node *new_node =
(struct Node *)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = *head_ref;
*head_ref = new_node;
}
/* Utility function to print a linked list */
void printList(struct Node *head)
{
while(head!=NULL)
{
printf("%d ",head->data);
head=head->next;
}
printf("\n");
}
/* Driver program to test above functions */
int main()
{
struct Node *head = NULL;
/* Create following 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);
printf("Given Linked List: ");
printList(head);
/* Let us delete the node with value 10 */
printf("\nDeleting node %d: ", head->next->next->data);
deleteNode(head, head->next->next);
299
Chapter 52. Delete a given node in Linked List under given constraints
printf("\nModified Linked List: ");
printList(head);
/* Let us delete the the first node */
printf("\nDeleting first node ");
deleteNode(head, head);
printf("\nModified Linked List: ");
printList(head);
getchar();
return 0;
}
Java
// Java program to delete a given node in linked list under given constraints
class LinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
void deleteNode(Node node, Node n) {
// When node to be deleted is head node
if (node == n) {
if (node.next == null) {
System.out.println("There is only one node. The list "
+ "can't be made empty ");
return;
}
/* Copy the data of next node to head */
node.data = node.next.data;
// store address of next node
n = node.next;
300
Chapter 52. Delete a given node in Linked List under given constraints
// Remove the link of next node
node.next = node.next.next;
// free memory
System.gc();
return;
}
// When not first node, follow the normal deletion process
// find the previous node
Node prev = node;
while (prev.next != null && prev.next != n) {
prev = prev.next;
}
// Check if node really exists in Linked List
if (prev.next == null) {
System.out.println("Given node is not present in Linked List");
return;
}
// Remove node from Linked List
prev.next = prev.next.next;
// Free memory
System.gc();
return;
}
/* Utility function to print a linked list */
void printList(Node head) {
while (head != null) {
System.out.print(head.data + " ");
head = head.next;
}
System.out.println("");
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.head = new Node(12);
list.head.next = new Node(15);
list.head.next.next = new Node(10);
list.head.next.next.next = new Node(11);
list.head.next.next.next.next = new Node(5);
301
Chapter 52. Delete a given node in Linked List under given constraints
list.head.next.next.next.next.next = new Node(6);
list.head.next.next.next.next.next.next = new Node(2);
list.head.next.next.next.next.next.next.next = new Node(3);
System.out.println("Given Linked List :");
list.printList(head);
System.out.println("");
// Let us delete the node with value 10
System.out.println("Deleting node :" + head.next.next.data);
list.deleteNode(head, head.next.next);
System.out.println("Modified Linked list :");
list.printList(head);
System.out.println("");
// Lets delete the first node
System.out.println("Deleting first Node");
list.deleteNode(head, head);
System.out.println("Modified Linked List");
list.printList(head);
}
}
// this code has been contributed by Mayank Jaiswal
Output:
Given Linked List: 12 15 10 11 5 6 2 3
Deleting node 10:
Modified Linked List: 12 15 11 5 6 2 3
Deleting first node
Modified Linked List: 15 11 5 6 2 3
Source
https://www.geeksforgeeks.org/delete-a-given-node-in-linked-list-under-given-constraints/
302
Chapter 53
Delete a linked list using
recursion
Delete a linked list using recursion - GeeksforGeeks
Delete the given linked list using recursion
Method
1) If head equal to NULL then linked list is empty, we simply return.
2) Recursively delete linked list after head node.
3) Delete head node.
// C++ program to recursively delete a linked list
#include <bits/stdc++.h>
/* Link list node */
struct Node {
int data;
struct Node* next;
};
/* Recursive Function to delete the entire linked list */
void deleteList(struct Node* head)
{
if (head == NULL)
return;
deleteList(head->next);
free(head);
}
/* Given a reference (pointer to pointer) to
the head of a list and an int, push a new
node on the front of the list. */
303
Chapter 53. Delete a linked list using recursion
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;
}
/* Drier program to test count function*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
/* Use push() to construct below list
1->12->1->4->1 */
push(&head, 1);
push(&head, 4);
push(&head, 1);
push(&head, 12);
push(&head, 1);
printf("\n Deleting linked list");
deleteList(head);
printf("\nLinked list deleted");
return 0;
}
Output:
Deleting linked list
Linked list deleted
Source
https://www.geeksforgeeks.org/delete-linked-list-using-recursion/
304
Chapter 54
Delete a node in a Doubly
Linked List
Delete a node in a Doubly Linked List - GeeksforGeeks
Doubly Link List Set 1| Introduction and Insertion
Write a function to delete a given node in a doubly linked list.
(a) Original Doubly Linked List
(a) After deletion of head node
305
Chapter 54. Delete a node in a Doubly Linked List
(a) After deletion of middle node
(a) After deletion of last node
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>
/* a node of the doubly linked list */
struct Node
306
Chapter 54. Delete a node in a Doubly Linked List
{
int data;
struct Node *next;
struct Node *prev;
};
/* Function to delete a node in a Doubly Linked List.
head_ref --> pointer to head node pointer.
del --> pointer to node to be deleted. */
void deleteNode(struct Node **head_ref, struct Node *del)
{
/* base case */
if(*head_ref == NULL || del == NULL)
return;
/* If node to be deleted is head node */
if(*head_ref == del)
*head_ref = del->next;
/* Change next only if node to be deleted is NOT the last node */
if(del->next != NULL)
del->next->prev = del->prev;
/* Change prev only if node to be deleted is NOT the first node */
if(del->prev != NULL)
del->prev->next = del->next;
/* Finally, free the memory occupied by del*/
free(del);
return;
}
/* 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));
/* put in the data */
new_node->data = new_data;
/* since we are adding at the begining,
prev is always NULL */
new_node->prev = NULL;
/* link the old list off the new node */
307
Chapter 54. Delete a node in a Doubly Linked List
new_node->next = (*head_ref);
/* change prev of head node to new node */
if((*head_ref) != NULL)
(*head_ref)->prev = new_node ;
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print nodes in a given doubly linked list
This function is same as printList() of singly linked lsit */
void printList(struct Node *node)
{
while(node!=NULL)
{
printf("%d ", node->data);
node = node->next;
}
}
/* Drier program to test above functions*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
/* Let us create the doubly linked list 10<->8<->4<->2 */
push(&head, 2);
push(&head, 4);
push(&head, 8);
push(&head, 10);
printf("\n Original Linked list ");
printList(head);
/* delete nodes from the doubly linked list */
deleteNode(&head, head); /*delete first node*/
deleteNode(&head, head->next); /*delete middle node*/
deleteNode(&head, head->next); /*delete last node*/
/* Modified linked list will be NULL<-8->NULL */
printf("\n Modified Linked list ");
printList(head);
getchar();
}
308
Chapter 54. Delete a node in a Doubly Linked List
Java
// Java program to delete a node from doubly linked list
class LinkedList {
static Node head = null;
class Node {
int data;
Node next, prev;
Node(int d) {
data = d;
next = prev = null;
}
}
/*Function to delete a node in a Doubly Linked List.
head_ref --> pointer to head node pointer.
del --> pointer to node to be deleted. */
void deleteNode(Node head_ref, Node del) {
/* base case */
if (head == null || del == null) {
return;
}
/* If node to be deleted is head node */
if (head == del) {
head = del.next;
}
/* Change next only if node to be deleted is NOT the last node */
if (del.next != null) {
del.next.prev = del.prev;
}
/* Change prev only if node to be deleted is NOT the first node */
if (del.prev != null) {
del.prev.next = del.next;
}
/* Finally, free the memory occupied by del*/
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);
/* since we are adding at the begining,
prev is always NULL */
new_node.prev = null;
/* link the old list off the new node */
new_node.next = (head);
/* change prev of head node to new node */
if ((head) != null) {
(head).prev = new_node;
}
/* move the head to point to the new node */
(head) = new_node;
}
/*Function to print nodes in a given doubly linked list
This function is same as printList() of singly linked lsit */
void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
/* Let us create the doubly linked list 10<->8<->4<->2 */
list.push(head, 2);
list.push(head, 4);
list.push(head, 8);
list.push(head, 10);
System.out.println("Original Linked list ");
list.printList(head);
/* delete nodes from the doubly linked list */
list.deleteNode(head, head); /*delete first node*/
list.deleteNode(head, head.next); /*delete middle node*/
310
Chapter 54. Delete a node in a Doubly Linked List
list.deleteNode(head, head.next); /*delete last node*/
System.out.println("");
/* Modified linked list will be NULL<-8->NULL */
System.out.println("Modified Linked List");
list.printList(head);
}
}
// This code has been contributed by Mayank Jaiswal
Python
# Program to delete a node in doubly linked list
# for Garbage collection
import gc
# A node of the doublly linked list
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
# Constructor for empty Doubly Linked List
def __init__(self):
self.head = None
# Function to delete a node in a Doubly Linked List.
# head_ref --> pointer to head node pointer.
# dele --> pointer to node to be deleted
def deleteNode(self, dele):
# Base Case
if self.head is None or dele is None:
return
# If node to be deleted is head node
if self.head == dele:
self.head = dele.next
# Change next only if node to be deleted is NOT
311
Chapter 54. Delete a node in a Doubly Linked List
# the last node
if dele.next is not None:
dele.next.prev = dele.prev
# Change prev only if node to be deleted is NOT
# the first node
if dele.prev is not None:
dele.prev.next = dele.next
# Finally, free the memory occupied by dele
# Call python garbage collector
gc.collect()
# Given a reference to the head of a list and an
# integer,inserts a new node on the front of list
def push(self, new_data):
# 1. Allocates node
# 2. Put the data in it
new_node = Node(new_data)
# 3. Make next of new node as head and
# previous as None (already None)
new_node.next = self.head
# 4. change prev of head node to new_node
if self.head is not None:
self.head.prev = new_node
# 5. move the head to point to the new node
self.head = new_node
def printList(self, node):
while(node is not None):
print node.data,
node = node.next
# Driver program to test the above functions
# Start with empty list
dll = DoublyLinkedList()
# Let us create the doubly linked list 10<->8<->4<->2
dll.push(2);
dll.push(4);
dll.push(8);
312
Chapter 54. Delete a node in a Doubly Linked List
dll.push(10);
print "\n Original Linked List",
dll.printList(dll.head)
# delete nodes from doubly linked list
dll.deleteNode(dll.head)
dll.deleteNode(dll.head.next)
dll.deleteNode(dll.head.next)
# Modified linked list will be NULL<-8->NULL
print "\n Modified Linked List",
dll.printList(dll.head)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Time Complexity: O(1)
Time Complexity: O(1)
Improved By : RiskCatalyst
Source
https://www.geeksforgeeks.org/delete-a-node-in-a-doubly-linked-list/
313
Chapter 55
Delete all occurrences of a given
key in a doubly linked list
Delete all occurrences of a given key in a doubly linked list - GeeksforGeeks
Given a doubly linked list and a key x. The problem is to delete all occurrences of the given
key x from the doubly linked list.
Examples:
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
/* C++ implementation to delete all occurrences
of a given key in a doubly linked list */
#include <bits/stdc++.h>
using namespace std;
/* a node of the doubly linked list */
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
/* Function to delete a node in a Doubly Linked List.
head_ref --> pointer to head node pointer.
del --> pointer to node to be deleted. */
void deleteNode(struct Node** head_ref, struct Node* del)
{
/* base case */
if (*head_ref == NULL || del == NULL)
return;
/* If node to be deleted is head node */
if (*head_ref == del)
*head_ref = del->next;
/* Change next only if node to be deleted
is NOT the last node */
if (del->next != NULL)
del->next->prev = del->prev;
/* Change prev only if node to be deleted
is NOT the first node */
if (del->prev != NULL)
del->prev->next = del->next;
/* Finally, free the memory occupied by del*/
free(del);
}
/* function to delete all occurrences of the given
key 'x' */
void deleteAllOccurOfX(struct Node** head_ref, int x)
{
/* if list is empty */
if ((*head_ref) == NULL)
return;
315
Chapter 55. Delete all occurrences of a given key in a doubly linked list
struct Node* current = *head_ref;
struct Node* next;
/* traverse the list up to the end */
while (current != NULL) {
/* if node found with the value 'x' */
if (current->data == x) {
/* save current's next node in the
pointer 'next' */
next = current->next;
/* delete the node pointed to by
'current' */
deleteNode(head_ref, current);
/* update current */
current = next;
}
/* else simply move to the next node */
else
current = current->next;
}
}
/* 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));
/* put in the data */
new_node->data = new_data;
/* since we are adding at the begining,
prev is always NULL */
new_node->prev = NULL;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* change prev of head node to new node */
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
316
Chapter 55. Delete all occurrences of a given key in a doubly linked list
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print nodes in a given doubly
linked list */
void printList(struct Node* head)
{
/* if list is empty */
if (head == NULL)
cout << "Doubly Linked list empty";
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
/* Driver program to test above functions*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
/* Create the doubly linked list:
2<->2<->10<->8<->4<->2<->5<->2 */
push(&head, 2);
push(&head, 5);
push(&head, 2);
push(&head, 4);
push(&head, 8);
push(&head, 10);
push(&head, 2);
push(&head, 2);
cout << "Original Doubly linked list:n";
printList(head);
int x = 2;
/* delete all occurrences of 'x' */
deleteAllOccurOfX(&head, x);
cout << "\nDoubly linked list after deletion of "
<< x << ":n";
printList(head);
317
Chapter 55. Delete all occurrences of a given key in a doubly linked list
return 0;
}
Output:
Original Doubly linked list:
2 2 10 8 4 2 5 2
Doubly linked list after deletion of 2:
10 8 4 5
Time Complexity: O(n)
Source
https://www.geeksforgeeks.org/delete-occurrences-given-key-doubly-linked-list/
318
Chapter 56
Delete all occurrences of a given
key in a linked list
Delete all occurrences of a given key in a linked list - GeeksforGeeks
Given a singly linked list, delete all occurrences of a given key in it. For example, consider
the following list.
Input: 2 -> 2 -> 1 -> 8 -> 2 -> 3 -> 2 -> 7
Key to delete = 2
Output: 1 -> 8 -> 3 -> 7
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.
// C Program to delete all occurrences of a given key in linked list
#include <stdio.h>
#include <stdlib.h>
// A linked list node
struct Node
{
int data;
struct Node *next;
};
/* Given a reference (pointer to pointer) to the head of a list
and an int, inserts a new node on the front of the list. */
319
Chapter 56. Delete all occurrences of a given key in a linked list
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
/* Given a reference (pointer to pointer) to the head of a list and
a key, deletes all occurrence of the given key in linked list */
void deleteKey(struct Node **head_ref, int key)
{
// Store head node
struct Node* temp = *head_ref, *prev;
// If head node itself holds the key or multiple occurrences of key
while (temp != NULL && temp->data == key)
{
*head_ref = temp->next; // Changed head
free(temp); // free old head
temp = *head_ref; // Change Temp
}
// Delete occurrences other than head
while (temp != NULL)
{
// Search for the key to be deleted, keep track of the
// previous node as we need to change 'prev->next'
while (temp != NULL && temp->data != key)
{
prev = temp;
temp = temp->next;
}
// If key was not present in linked list
if (temp == NULL) return;
// Unlink the node from linked list
prev->next = temp->next;
free(temp); // Free memory
//Update Temp for next iteration of outer loop
temp = prev->next;
}
}
// This function prints contents of linked list starting from
320
Chapter 56. Delete all occurrences of a given key in a linked list
// the given node
void printList(struct Node *node)
{
while (node != NULL)
{
printf(" %d ", node->data);
node = node->next;
}
}
/* Drier program to test above functions*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
push(&head, 7);
push(&head, 2);
push(&head, 3);
push(&head, 2);
push(&head, 8);
push(&head, 1);
push(&head, 2);
push(&head, 2);
int key = 2; // key to delete
puts("Created Linked List: ");
printList(head);
deleteKey(&head, key);
puts("\nLinked List after Deletion of 1: ");
printList(head);
return 0;
}
Output:
Created Linked List:
2 2 1 8 2 3 2 7
Linked List after Deletion of 1:
1 8 3 7
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
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:
Input: 10 <=> 8 <=> 4 <=> 11 <=> 9, X = 9
Output: 8 <=> 4 <=> 9
Input: 4 <=> 4 <=> 2 <=> 1 <=> 3 <=> 5, X = 2
Output: 2 <=> 1
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.
// C++ implementation to delete all
// the nodes from the doubly
// linked list that are greater than
// the specified value x
#include <bits/stdc++.h>
using namespace std;
// Node of the doubly linked list
struct Node {
323
Chapter 57. Delete all the nodes from the doubly linked list that are greater than a given
value
int data;
Node *prev, *next;
};
// 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 = (Node*)malloc(sizeof(struct Node));
// put in the data
new_node->data = new_data;
// since we are adding at the begining,
// prev is always NULL
new_node->prev = NULL;
// link the old list off the new node
new_node->next = (*head_ref);
// change prev of head node to new node
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
// move the head to point to the new node
(*head_ref) = new_node;
}
// function to delete a node in a Doubly Linked List.
// head_ref --> pointer to head node pointer.
// del --> pointer to node to be deleted
void deleteNode(Node** head_ref, Node* del)
{
// base case
if (*head_ref == NULL || del == NULL)
return;
// If node to be deleted is head node
if (*head_ref == del)
*head_ref = del->next;
// Change next only if node to be
// deleted is NOT the last node
if (del->next != NULL)
del->next->prev = del->prev;
// Change prev only if node to be
324
Chapter 57. Delete all the nodes from the doubly linked list that are greater than a given
value
// deleted is NOT the first node
if (del->prev != NULL)
del->prev->next = del->next;
// Finally, free the memory occupied by del
free(del);
return;
}
// function to delete all the nodes
// from the doubly linked
// list that are greater than the
// specified value x
void deleteGreaterNodes(Node** head_ref, int x)
{
Node* ptr = *head_ref;
Node* next;
while (ptr != NULL) {
next = ptr->next;
// if true, delete node 'ptr'
if (ptr->data > x)
deleteNode(head_ref, ptr);
ptr = next;
}
}
// function to print nodes in a
// given doubly linked list
void printList(Node* head)
{
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
// Driver program to test above
int main()
{
// start with the empty list
Node* head = NULL;
// create the doubly linked list
// 10<->8<->4<->11<->9
push(&head, 9);
push(&head, 11);
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;
cout << "Original List: ";
printList(head);
deleteGreaterNodes(&head, x);
cout << "\nModified List: ";
printList(head);
}
Output:
Original List: 10 8 4 11 9
Modified List: 8 4 9
Time Complexity: O(N)
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
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:
Input : list: 7->3->4->8->5->1
x = 6
Output : 3->4->5->1
Input : list: 1->8->7->3->7->10
x = 7
Output : 1->7->3->7
Source: Microsoft Interview Experience | Set 169.
Approach: This is mainly a variation of the post which deletes first occurrence of a given
key.
We need to first check for all occurrences at head node which are greater than ‘x’, delete
them and change the head node appropriately. Then we need to check for all occurrences
inside a loop and delete them one by one.
// C++ implementation to delete all the nodes from the list
// that are greater than the specified value x
#include <bits/stdc++.h>
using namespace std;
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;
};
// function to get a new node
Node* getNode(int data)
{
Node* newNode = new Node;
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// function to delete all the nodes from the list
// that are greater than the specified value x
void deleteGreaterNodes(Node** head_ref, int x)
{
Node *temp = *head_ref, *prev;
// If head node itself holds the value greater than 'x'
while (temp != NULL && temp->data > x) {
*head_ref = temp->next; // Changed head
free(temp); // free old head
temp = *head_ref; // Change temp
}
// Delete occurrences other than head
while (temp != NULL) {
// Search for the node to be deleted,
// keep track of the previous node as we
// need to change 'prev->next'
while (temp != NULL && temp->data <= x) {
prev = temp;
temp = temp->next;
}
// If required value node was not present
// in linked list
if (temp == NULL)
return;
// Unlink the node from linked list
prev->next = temp->next;
delete temp; // Free memory
328
Chapter 58. Delete all the nodes from the list that are greater than x
// Update Temp for next iteration of
// outer loop
temp = prev->next;
}
}
// function to a print a linked list
void printList(Node* head)
{
while (head) {
cout << head->data << " ";
head = head->next;
}
}
// Driver program to test above
int main()
{
// Create list: 7->3->4->8->5->1
Node* head = getNode(7);
head->next = getNode(3);
head->next->next = getNode(4);
head->next->next->next = getNode(8);
head->next->next->next->next = getNode(5);
head->next->next->next->next->next = getNode(1);
int x = 6;
cout << "Original List: ";
printList(head);
deleteGreaterNodes(&head, x);
cout << "\nModified List: ";
printList(head);
return 0;
}
Output:
Original List: 7 3 4 8 5 1
Modified List: 3 4 5 1
Time Complexity: O(n).
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
Delete alternate nodes of a
Linked List
Delete alternate nodes of a Linked List - GeeksforGeeks
Given a Singly Linked List, starting from the second node delete all alternate nodes of it.
For example, if the given linked list is 1->2->3->4->5 then your function should convert it
to 1->3->5, and if the given linked list is 1->2->3->4 then convert it to 1->3.
Method 1 (Iterative)
Keep track of previous of the node to be deleted. First change the next link of previous
node and then free the memory allocated for the node.
C/C++
// C program to remove alternate nodes of a linked list
#include<stdio.h>
#include<stdlib.h>
/* A linked list node */
struct Node
{
int data;
struct Node *next;
};
/* deletes alternate nodes of a list starting with head */
void deleteAlt(struct Node *head)
{
if (head == NULL)
return;
/* Initialize prev and node to be deleted */
struct Node *prev = head;
331
Chapter 59. Delete alternate nodes of a Linked List
struct Node *node = head->next;
while (prev != NULL && node != NULL)
{
/* Change next link of previous node */
prev->next = node->next;
/* Free memory */
free(node);
/* Update prev and node */
prev = prev->next;
if (prev != NULL)
node = prev->next;
}
}
/* UTILITY FUNCTIONS TO TEST fun1() and fun2() */
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print nodes in a given linked list */
void printList(struct Node *node)
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
}
/* Drier program to test above functions */
332
Chapter 59. Delete alternate nodes of a Linked List
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
/* Using push() to construct below list
1->2->3->4->5 */
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
printf("\nList before calling deleteAlt() \n");
printList(head);
deleteAlt(head);
printf("\nList after calling deleteAlt() \n");
printList(head);
return 0;
}
Java
// Java program to delete alternate nodes of a linked list
class LinkedList
{
Node head; // head of list
/* Linked list Node*/
class Node
{
int data;
Node next;
Node(int d) {data = d; next = null; }
}
void deleteAlt()
{
if (head == null)
return;
Node prev = head;
Node now = head.next;
while (prev != null && now != null)
333
Chapter 59. Delete alternate nodes of a Linked List
{
/* Change next link of previus node */
prev.next = now.next;
/* Free node */
now = null;
/*Update prev and now */
prev = prev.next;
if (prev != null)
now = prev.next;
}
}
/* Utility functions */
/* Inserts a new Node at front of the list. */
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
/* Function to print linked list */
void printList()
{
Node temp = head;
while(temp != null)
{
System.out.print(temp.data+" ");
temp = temp.next;
}
System.out.println();
}
/* Drier program to test above functions */
public static void main(String args[])
{
LinkedList llist = new LinkedList();
334
Chapter 59. Delete alternate nodes of a Linked List
/* Constructed Linked List is 1->2->3->4->5->null */
llist.push(5);
llist.push(4);
llist.push(3);
llist.push(2);
llist.push(1);
System.out.println("Linked List before calling deleteAlt() ");
llist.printList();
llist.deleteAlt();
System.out.println("Linked List after calling deleteAlt() ");
llist.printList();
}
}
/* This code is contributed by Rajat Mishra */
Output:
List before calling deleteAlt()
1 2 3 4 5
List after calling deleteAlt()
1 3 5
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.
/* deletes alternate nodes of a list starting with head */
void deleteAlt(struct Node *head)
{
if (head == NULL)
return;
struct Node *node = head->next;
if (node == NULL)
return;
/* Change the next link of head */
head->next = node->next;
/* free memory allocated for node */
free(node);
335
Chapter 59. Delete alternate nodes of a Linked List
/* Recursively call for the new next of head */
deleteAlt(head->next);
}
Time Complexity: O(n)
Source
https://www.geeksforgeeks.org/delete-alternate-nodes-of-a-linked-list/
336
Chapter 60
Delete last occurrence of an
item from linked list
Delete last occurrence of an item from linked list - GeeksforGeeks
Given a liked list and a key to be deleted. Delete last occurrence of key from linked. The
list may have duplicates.
Examples:
Input: 1->2->3->5->2->10, key = 2
Output: 1->2->3->5->10
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.
// A C++ program to demonstrate deletion of last
// Node in singly linked list
#include <bits/stdc++.h>
// A linked list Node
struct Node {
int key;
struct Node* next;
};
void deleteLast(Node* head, int key)
{
// Initialize previous of Node to be deleted
Node* x = NULL;
// Start from head and find the Node to be
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;
}
// key occurs at-least once
if (x != NULL) {
// Copy key of next Node to x
x->key = x->next->key;
// Store and unlink next
temp = x->next;
x->next = x->next->next;
// Free memory for next
delete temp;
}
}
/* Utility function to create a new node with
given key */
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->next = NULL;
return temp;
}
// This function prints contents of linked list
// starting from the given Node
void printList(struct Node* node)
{
while (node != NULL) {
printf(" %d ", node->key);
node = node->next;
}
}
/* Drier program to test above functions*/
int main()
{
338
Chapter 60. Delete last occurrence of an item from linked list
/* Start with the empty list */
struct Node* head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(5);
head->next->next->next->next = newNode(2);
head->next->next->next->next->next = newNode(10);
puts("Created Linked List: ");
printList(head);
deleteLast(head, 2);
puts("\nLinked List after Deletion of 1: ");
printList(head);
return 0;
}
Output:
Created Linked List:
1 2 3 5 2 10
Linked List after Deletion of 1:
1 2 3 5 10
The above solution doesn’t work when the node to be deleted is the last node.
Following solution handles all cases.
// A C program to demonstrate deletion of last
// Node in singly linked list
#include <stdio.h>
#include <stdlib.h>
// A linked list Node
struct Node {
int data;
struct Node* next;
};
// Function to delete the last occurrence
void deleteLast(struct Node* head, int x)
{
struct Node *temp = head, *ptr = NULL;
while (temp) {
// If found key, update
if (temp->data == x)
ptr = temp;
temp = temp->next;
339
Chapter 60. Delete last occurrence of an item from linked list
// If the last occurrence is the last node
if (ptr != NULL && ptr->next == NULL) {
temp = head;
while (temp->next != ptr)
temp = temp->next;
temp->next = NULL;
}
// If it is not the last node
if (ptr != NULL && ptr->next != NULL) {
ptr->data = ptr->next->data;
temp = ptr->next;
ptr->next = ptr->next->next;
free(temp);
}
}
/* Utility function to create a new node with
given key */
struct Node* newNode(int x)
{
struct Node* node = malloc(sizeof(struct Node*));
node->data = x;
node->next = NULL;
return node;
}
// This function prints contents of linked list
// starting from the given Node
void display(struct Node* head)
{
struct Node* temp = head;
if (head == NULL) {
printf("NULL\n");
return;
}
while (temp != NULL) {
printf("%d --> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
/* Drier program to test above functions*/
int main()
{
340
Chapter 60. Delete last occurrence of an item from linked list
struct 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->next->next->next->next->next = newNode(4);
head->next->next->next->next->next->next = newNode(4);
printf("Created Linked list: ");
display(head);
deleteLast(head, 4);
printf("List after deletion of 4: ");
display(head);
return 0;
}
Output:
Created Linked List:
1 2 3 4 5 4 4
Linked List after Deletion of 1:
1 2 3 4 5 4
Source
https://www.geeksforgeeks.org/delete-last-occurrence-of-an-item-from-linked-list/
341
Chapter 61
Delete middle of linked list
Delete middle of linked list - GeeksforGeeks
Given a singly linked list, delete middle of the linked list. For example, if given linked list
is 1->2->3->4->5 then linked list should be modified to 1->2->4->5
If there are even nodes, then there would be two middle nodes, we need to delete the second
middle element. For example, if given linked list is 1->2->3->4->5->6 then it should be
modified to 1->2->3->5->6.
If the input linked list is NULL, then it should remain NULL.
If the input linked list has 1 node, then this node should be deleted and new head should
be returned.
A Simple Solution is to first count number of nodes in linked list, then delete n/2’th node
using the simple deletion process.
The above solution requires two traversals of linked list. We can delete middle node using
one traversal. The idea is to use two pointers, slow_ptr and fast_ptr. Both pointers start
from head of list. When fast_ptr reaches end, slow_ptr reaches middle. This idea is same
as the one used in method 2 of this post. The additional thing in this post is to keep track
of previous of middle so that we can delete middle.
Below is C++ implementation.
// C++ program to delete middle of a linked list
#include<bits/stdc++.h>
using namespace std;
/* Link list Node */
struct Node
{
int data;
struct Node* next;
};
342
Chapter 61. Delete middle of linked list
// Deletes middle node and returns head of the
// modified list
struct Node* deleteMid(struct Node *head)
{
// Base cases
if (head == NULL)
return NULL;
if (head->next == NULL)
{
delete head;
return NULL;
}
// Initialize slow and fast pointers to reach
// middle of linked list
struct Node *slow_ptr = head;
struct Node *fast_ptr = head;
// Find the middle and previous of middle.
struct Node *prev; // To store previous of slow_ptr
while (fast_ptr != NULL && fast_ptr->next != NULL)
{
fast_ptr = fast_ptr->next->next;
prev = slow_ptr;
slow_ptr = slow_ptr->next;
}
//Delete the middle node
prev->next = slow_ptr->next;
delete slow_ptr;
return head;
}
// A utility function to print a given linked list
void printList(struct Node *ptr)
{
while (ptr != NULL)
{
cout << ptr->data << "->";
ptr = ptr->next;
}
cout << "NULL\n";
}
// Utility function to create a new node.
Node *newNode(int data)
343
Chapter 61. Delete middle of linked list
{
struct Node *temp = new Node;
temp->data = data;
temp->next = NULL;
return temp;
}
/* Drier program to test above function*/
int main()
{
/* Start with the empty list */
struct Node* head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
cout << "Gven Linked List\n";
printList(head);
head = deleteMid(head);
cout << "Linked List after deletion of middle\n";
printList(head);
return 0;
}
Output :
Gven Linked List
1->2->3->4->NULL
Linked List after deletion of middle
1->2->4->NULL
Source
https://www.geeksforgeeks.org/delete-middle-of-linked-list/
344
Chapter 62
Delete multiple occurrences of
key in Linked list using double
pointer
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.
Input: 2 -> 2 -> 4 -> 3 -> 2
Key to delete = 2
Output: 4 -> 3
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.
// CPP program to delete multiple
345
Chapter 62. Delete multiple occurrences of key in Linked list using double pointer
// occurrences of a key using single
// loop.
#include <iostream>
using namespace std;
// A linked list node
struct Node {
int data;
struct Node* next;
};
struct Node* head = NULL;
void printList(struct Node* node)
{
while (node != NULL) {
printf(" %d ", node->data);
node = node->next;
}
}
void push(int new_data)
{
struct Node* new_node = new Node;
new_node->data = new_data;
new_node->next = (head);
(head) = new_node;
}
void deleteEntry(int key)
{
// Start from head
struct Node** pp = &head;
while (*pp) {
struct Node* entry = *pp;
// If key found, then put
// next at the address of pp
// delete entry.
if (entry->data == key) {
*pp = entry->next;
delete (entry);
}
// Else move to next
else
pp = &(entry->next);
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);
int key = 2; // key to delete
puts("Created Linked List: ");
printList(head);
printf("\n");
deleteEntry(key);
printf("\nLinked List after Deletion of 2: \n");
printList(head);
return 0;
}
Output:
Created Linked List:
2 3 4 2 2
Linked List after Deletion of 2:
3 4
Source
https://www.geeksforgeeks.org/delete-multiple-occurrences-of-key-in-linked-list-using-double-pointer/
347
Chapter 63
Delete nodes which have a
greater value on right side
Delete nodes which have a greater value on right side - GeeksforGeeks
Given a singly linked list, remove all the nodes which have a greater value on right side.
Examples:
a) The list 12->15->10->11->5->6->2->3->NULL should be changed to 15->11->6->3-
>NULL. Note that 12, 10, 5 and 2 have been deleted because there is a greater value on the
right side.
When we examine 12, we see that after 12 there is one node with value greater than 12 (i.e.
15), so we delete 12.
When we examine 15, we find no node after 15 that has value greater than 15 so we keep
this node.
When we go like this, we get 15->6->3
b) The list 10->20->30->40->50->60->NULL should be changed to 60->NULL. Note that
10, 20, 30, 40 and 50 have been deleted because they all have a greater value on the right
side.
c) The list 60->50->40->30->20->10->NULL should not be changed.
Method 1 (Simple)
Use two loops. In the outer loop, pick nodes of the linked list one by one. In the inner loop,
check if there exist a node whose value is greater than the picked node. If there exists a
node whose value is greater, then delete the picked node.
Time Complexity: O(n^2)
Method 2 (Use Reverse)
Thanks to Paras for providing the below algorithm.
1. Reverse the list.
2. Traverse the reversed list. Keep max till now. If next node is less than max, then delete
the next node, otherwise max = next node.
3. Reverse the list again to retain the original order.
348
Chapter 63. Delete nodes which have a greater value on right side
Time Complexity: O(n)
Thanks to R.Srinivasan for providing below code.
// C program to delete nodes which have a greater value on
// right side
#include <stdio.h>
#include <stdlib.h>
/* structure of a linked list node */
struct Node {
int data;
struct Node* next;
};
/* prototype for utility functions */
void reverseList(struct Node** headref);
void _delLesserNodes(struct Node* head);
/* Deletes nodes which have a node with greater value node
on left side */
void delLesserNodes(struct Node** head_ref)
{
/* 1) Reverse the linked list */
reverseList(head_ref);
/* 2) In the reversed list, delete nodes which have a node
with greater value node on left side. Note that head
node is never deleted because it is the leftmost node.*/
_delLesserNodes(*head_ref);
/* 3) Reverse the linked list again to retain the
original order */
reverseList(head_ref);
}
/* Deletes nodes which have greater value node(s) on left side */
void _delLesserNodes(struct Node* head)
{
struct Node* current = head;
/* Initialize max */
struct Node* maxnode = head;
struct Node* temp;
while (current != NULL && current->next != NULL) {
349
Chapter 63. Delete nodes which have a greater value on right side
/* If current is smaller than max, then delete current */
if (current->next->data < maxnode->data) {
temp = current->next;
current->next = temp->next;
free(temp);
}
/* If current is greater than max, then update max and
move current */
else {
current = current->next;
maxnode = current;
}
}
}
/* Utility function to insert a node at the begining */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = *head_ref;
*head_ref = new_node;
}
/* Utility function to reverse a linked list */
void reverseList(struct Node** headref)
{
struct Node* current = *headref;
struct Node* prev = NULL;
struct Node* next;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*headref = prev;
}
/* Utility function to print a linked list */
void printList(struct Node* head)
{
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
350
Chapter 63. Delete nodes which have a greater value on right side
/* Driver program to test above functions */
int main()
{
struct Node* head = NULL;
/* Create following 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);
printf("Given Linked List \n");
printList(head);
delLesserNodes(&head);
printf("Modified Linked List \n");
printList(head);
return 0;
}
Java
// Java program to delete nodes which have a greater value on
// right side
class LinkedList {
Node head; // head of list
/* Linked list Node*/
class Node {
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
/* Deletes nodes which have a node with greater
351
Chapter 63. Delete nodes which have a greater value on right side
value node on left side */
void delLesserNodes()
{
/* 1.Reverse the linked list */
reverseList();
/* 2) In the reversed list, delete nodes which
have a node with greater value node on left
side. Note that head node is never deleted
because it is the leftmost node.*/
_delLesserNodes();
/* 3) Reverse the linked list again to retain
the original order */
reverseList();
}
/* Deletes nodes which have greater value node(s)
on left side */
void _delLesserNodes()
{
Node current = head;
/* Initialise max */
Node maxnode = head;
Node temp;
while (current != null && current.next != null) {
/* If current is smaller than max, then delete
current */
if (current.next.data < maxnode.data) {
temp = current.next;
current.next = temp.next;
temp = null;
}
/* If current is greater than max, then update
max and move current */
else {
current = current.next;
maxnode = current;
}
}
}
/* Utility functions */
/* Inserts a new Node at front of the list. */
352
Chapter 63. Delete nodes which have a greater value on right side
void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
/* Function to reverse the linked list */
void reverseList()
{
Node current = head;
Node prev = null;
Node next;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
}
/* Function to print linked list */
void printList()
{
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
/* Drier program to test above functions */
public static void main(String args[])
{
LinkedList llist = new LinkedList();
/* Constructed Linked List is 12->15->10->11->
5->6->2->3 */
llist.push(3);
llist.push(2);
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);
System.out.println("Given Linked List");
llist.printList();
llist.delLesserNodes();
System.out.println("Modified Linked List");
llist.printList();
}
} /* This code is contributed by Rajat Mishra */
Output:
Given Linked List
12 15 10 11 5 6 2 3
Modified Linked List
15 11 6 3
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
Deletion from a Circular Linked
List
Deletion from a Circular Linked List - GeeksforGeeks
We have already discussed about circular linked list and traversal in a circular linked list
in the below articles:
Introduction to circular linked list
Traversal in a circular linked list
In this article we will learn about deleting a node from a cicular linked list. Consider the
linked list as shown below:
We will be given a node and our task is to delete that node from the circular linked list.
Examples:
Input : 2->5->7->8->10->(head node)
data = 5
Output : 2->7->8->10->(head node)
Input : 2->5->7->8->10->(head node)
7
Output : 2->5->8->10->2(head node)
Algorithm
355
Chapter 64. Deletion from a Circular Linked List
Case 1: List is empty.
• If the list is empty we will simply return.
Case 2:List is not empty
• 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.
Complete C program to demonstrate deletion in Circular Linked List:
// C program to delete a given key from
// linked list.
#include<stdio.h>
#include<stdlib.h>
/* structure for a node */
struct Node
{
int data;
struct Node *next;
};
/* Function to insert a node at the beginning of
a Circular linked list */
void push(struct Node **head_ref, int data)
{
// Create a new node and make head as next
// of it.
struct Node *ptr1 =
(struct Node *)malloc(sizeof(struct Node));
ptr1->data = data;
ptr1->next = *head_ref;
356
Chapter 64. Deletion from a Circular Linked List
/* If linked list is not NULL then set the
next of last node */
if (*head_ref != NULL)
{
// Find the node before head and update
// next of it.
struct Node *temp = *head_ref;
while (temp->next != *head_ref)
temp = temp->next;
temp->next = ptr1;
}
else
ptr1->next = ptr1; /*For the first node */
*head_ref = ptr1;
}
/* Function to print nodes in a given
circular linked list */
void printList(struct Node *head)
{
struct Node *temp = head;
if (head != NULL)
{
do
{
printf("%d ", temp->data);
temp = temp->next;
}
while (temp != head);
}
printf("\n");
}
/* Function to delete a given node from the list */
void deleteNode(struct Node *head, int key)
{
if (head == NULL)
return;
// Find the required node
struct Node *curr = head, *prev;
while (curr->data != key)
{
if (curr->next == head)
{
printf("\nGiven node is not found"
357
Chapter 64. Deletion from a Circular Linked List
" in the list!!!");
break;
}
prev = curr;
curr = curr -> next;
}
// Check if node is only node
if (curr->next == head)
{
head = NULL;
free(curr);
return;
}
// If more than one node, check if
// it is first node
if (curr == head)
{
prev = head;
while (prev -> next != head)
prev = prev -> next;
head = curr->next;
prev->next = head;
free(curr);
}
// check if node is last node
else if (curr -> next == head)
{
prev->next = head;
free(curr);
}
else
{
prev->next = curr->next;
free(curr);
}
}
/* Driver program to test above functions */
int main()
{
/* Initialize lists as empty */
struct Node *head = NULL;
/* Created linked list will be 2->5->7->8->10 */
358
Chapter 64. Deletion from a Circular Linked List
push(&head, 2);
push(&head, 5);
push(&head, 7);
push(&head, 8);
push(&head, 10);
printf("List Before Deletion: ");
printList(head);
deleteNode(head, 7);
printf("List After Deletion: ");
printList(head);
return 0;
}
Output:
List Before Deletion: 10 8 7 5 2
List After Deletion: 10 8 5 2
Source
https://www.geeksforgeeks.org/deletion-circular-linked-list/
359
Chapter 65
Detect and Remove Loop in a
Linked List
Detect and Remove Loop in a Linked List - GeeksforGeeks
Write a function detectAndRemoveLoop() that checks whether a given Linked List contains
loop and if loop is present then removes the loop and returns true. And if the list doesn’t
contain loop then returns false. Below diagram shows a linked list with a loop. detectAn-
dRemoveLoop() must change the below list to 1->2->3->4->5->NULL.
We also recommend to read following post as a prerequisite of the solution discussed here.
Write a C function to detect loop in a linked list
Before trying to remove the loop, we must detect it. Techniques discussed in the above post
can be used to detect loop. To remove loop, all we need to do is to get pointer to the last
node of the loop. For example, node with value 5 in the above diagram. Once we have
pointer to the last node, we can make the next of this node as NULL and loop is gone.
We can easily use Hashing or Visited node techniques (discussed in the above mentioned
post) to get the pointer to the last node. Idea is simple: the very first node whose next is
already visited (or hashed) is the last node.
We can also use Floyd Cycle Detection algorithm to detect and remove the loop. In the
Floyd’s algo, the slow and fast pointers meet at a loop node. We can use this loop node
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>
/* Link list node */
struct Node
{
int data;
struct Node* next;
};
/* Function to remove loop. Used by detectAndRemoveLoop() */
void removeLoop(struct Node *, struct Node *);
/* This function detects and removes loop in the list
If loop was there in the list then it returns 1,
otherwise returns 0 */
int detectAndRemoveLoop(struct Node *list)
{
struct Node *slow_p = list, *fast_p = list;
while (slow_p && fast_p && fast_p->next)
{
slow_p = slow_p->next;
fast_p = fast_p->next->next;
/* If slow_p and fast_p meet at some point then there
is a loop */
if (slow_p == fast_p)
{
removeLoop(slow_p, list);
/* Return 1 to indicate that loop is found */
return 1;
}
}
361
Chapter 65. Detect and Remove Loop in a Linked List
/* Return 0 to indeciate that ther is no loop*/
return 0;
}
/* Function to remove loop.
loop_node --> Pointer to one of the loop nodes
head --> Pointer to the start node of the linked list */
void removeLoop(struct Node *loop_node, struct Node *head)
{
struct Node *ptr1;
struct Node *ptr2;
/* Set a pointer to the beging of the Linked List and
move it one by one to find the first node which is
part of the Linked List */
ptr1 = head;
while (1)
{
/* Now start a pointer from loop_node and check if it ever
reaches ptr2 */
ptr2 = loop_node;
while (ptr2->next != loop_node && ptr2->next != ptr1)
ptr2 = ptr2->next;
/* If ptr2 reahced ptr1 then there is a loop. So break the
loop */
if (ptr2->next == ptr1)
break;
/* 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;
}
/* Function to print linked list */
void printList(struct Node *node)
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
}
362
Chapter 65. Detect and Remove Loop in a Linked List
struct Node *newNode(int key)
{
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = key;
temp->next = NULL;
return temp;
}
/* Drier program to test above function*/
int main()
{
struct Node *head = newNode(50);
head->next = newNode(20);
head->next->next = newNode(15);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(10);
/* Create a loop for testing */
head->next->next->next->next->next = head->next->next;
detectAndRemoveLoop(head);
printf("Linked List after removing loop \n");
printList(head);
return 0;
}
Java
// Java program to detect and remove loop in linked list
class LinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
// Function that detects loop in the list
363
Chapter 65. Detect and Remove Loop in a Linked List
int detectAndRemoveLoop(Node node) {
Node slow = node, fast = node;
while (slow != null && fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
// If slow and fast meet at same point then loop is present
if (slow == fast) {
removeLoop(slow, node);
return 1;
}
}
return 0;
}
// Function to remove loop
void removeLoop(Node loop, Node curr) {
Node ptr1 = null, ptr2 = null;
/* Set a pointer to the beging of the Linked List and
move it one by one to find the first node which is
part of the Linked List */
ptr1 = curr;
while (1 == 1) {
/* Now start a pointer from loop_node and check if it ever
reaches ptr2 */
ptr2 = loop;
while (ptr2.next != loop && ptr2.next != ptr1) {
ptr2 = ptr2.next;
}
/* If ptr2 reahced ptr1 then there is a loop. So break the
loop */
if (ptr2.next == ptr1) {
break;
}
/* 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;
}
// Function to print the linked list
364
Chapter 65. Detect and Remove Loop in a Linked List
void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
// Driver program to test above functions
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.head = new Node(50);
list.head.next = new Node(20);
list.head.next.next = new Node(15);
list.head.next.next.next = new Node(4);
list.head.next.next.next.next = new Node(10);
// Creating a loop for testing
head.next.next.next.next.next = head.next.next;
list.detectAndRemoveLoop(head);
System.out.println("Linked List after removing loop : ");
list.printList(head);
}
}
// This code has been contributed by Mayank Jaiswal
Python
# Python program to detect and remove loop in linked list
# Node class
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
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
# If slow_p and fast_p meet at some poin
# then there is a loop
if slow_p == fast_p:
self.removeLoop(slow_p)
# Return 1 to indicate that loop if found
return 1
# Return 0 to indicate that there is no loop
return 0
# Function to remove loop
# loop node-> Pointer to one of the loop nodes
# head --> Pointer to the start node of the
# linked list
def removeLoop(self, loop_node):
# Set a pointer to the beginning of the linked
# list and move it one by one to find the first
# node which is part of the linked list
ptr1 = self.head
while(1):
# Now start a pointer from loop_node and check
# if it ever reaches ptr2
ptr2 = loop_node
while(ptr2.next!= loop_node and ptr2.next !=ptr1):
ptr2 = ptr2.next
# If ptr2 reached ptr1 then there is a loop.
# So break the loop
if ptr2.next == ptr1 :
break
ptr1 = ptr1.next
# After the end of loop ptr2 is the lsat node of
# the loop. So make next of ptr2 as NULL
ptr2.next = None
# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Utility function to prit the linked LinkedList
def printList(self):
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)
# Create a loop for testing
llist.head.next.next.next.next.next = llist.head.next.next
llist.detectAndRemoveLoop()
print "Linked List after removing loop"
llist.printList()
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Linked List after removing loop
50 20 15 4 10
Method 2 (Better Solution)
This method is also dependent on Floyd’s Cycle detection algorithm.
1) Detect Loop using Floyd’s Cycle detection algo and get the pointer to a loop node.
2) Count the number of nodes in loop. Let the count be k.
3) Fix one pointer to the head and another to kth node from head.
4) Move both pointers at the same pace, they will meet at loop starting node.
5) Get pointer to the last node of loop and make next of it as NULL.
Thanks to WgpShashank for suggesting this method.
C
#include<stdio.h>
#include<stdlib.h>
/* Link list node */
struct Node
{
int data;
367
Chapter 65. Detect and Remove Loop in a Linked List
struct Node* next;
};
/* Function to remove loop. */
void removeLoop(struct Node *, struct Node *);
/* This function detects and removes loop in the list
If loop was there in the list then it returns 1,
otherwise returns 0 */
int detectAndRemoveLoop(struct Node *list)
{
struct Node *slow_p = list, *fast_p = list;
while (slow_p && fast_p && fast_p->next)
{
slow_p = slow_p->next;
fast_p = fast_p->next->next;
/* If slow_p and fast_p meet at some point then there
is a loop */
if (slow_p == fast_p)
{
removeLoop(slow_p, list);
/* Return 1 to indicate that loop is found */
return 1;
}
}
/* Return 0 to indeciate that ther is no loop*/
return 0;
}
/* Function to remove loop.
loop_node --> Pointer to one of the loop nodes
head --> Pointer to the start node of the linked list */
void removeLoop(struct Node *loop_node, struct Node *head)
{
struct Node *ptr1 = loop_node;
struct Node *ptr2 = loop_node;
// Count the number of nodes in loop
unsigned int k = 1, i;
while (ptr1->next != ptr2)
{
ptr1 = ptr1->next;
k++;
}
368
Chapter 65. Detect and Remove Loop in a Linked List
// Fix one pointer to head
ptr1 = head;
// And the other pointer to k nodes after head
ptr2 = head;
for (i = 0; i < k; i++)
ptr2 = ptr2->next;
/* Move both pointers at the same pace,
they will meet at loop starting node */
while (ptr2 != ptr1)
{
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}
// Get pointer to the last node
ptr2 = ptr2->next;
while (ptr2->next != ptr1)
ptr2 = ptr2->next;
/* Set the next node of the loop ending node
to fix the loop */
ptr2->next = NULL;
}
/* Function to print linked list */
void printList(struct Node *node)
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
}
struct Node *newNode(int key)
{
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = key;
temp->next = NULL;
return temp;
}
/* Driver program to test above function*/
int main()
{
369
Chapter 65. Detect and Remove Loop in a Linked List
struct Node *head = newNode(50);
head->next = newNode(20);
head->next->next = newNode(15);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(10);
/* Create a loop for testing */
head->next->next->next->next->next = head->next->next;
detectAndRemoveLoop(head);
printf("Linked List after removing loop \n");
printList(head);
return 0;
}
Java
// Java program to detect and remove loop in linked list
class LinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
// Function that detects loop in the list
int detectAndRemoveLoop(Node node) {
Node slow = node, fast = node;
while (slow != null && fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
// If slow and fast meet at same point then loop is present
if (slow == fast) {
removeLoop(slow, node);
return 1;
}
}
370
Chapter 65. Detect and Remove Loop in a Linked List
return 0;
}
// Function to remove loop
void removeLoop(Node loop, Node head) {
Node ptr1 = loop;
Node ptr2 = loop;
// Count the number of nodes in loop
int k = 1, i;
while (ptr1.next != ptr2) {
ptr1 = ptr1.next;
k++;
}
// Fix one pointer to head
ptr1 = head;
// And the other pointer to k nodes after head
ptr2 = head;
for (i = 0; i < k; i++) {
ptr2 = ptr2.next;
}
/* Move both pointers at the same pace,
they will meet at loop starting node */
while (ptr2 != ptr1) {
ptr1 = ptr1.next;
ptr2 = ptr2.next;
}
// Get pointer to the last node
ptr2 = ptr2.next;
while (ptr2.next != ptr1) {
ptr2 = ptr2.next;
}
/* Set the next node of the loop ending node
to fix the loop */
ptr2.next = null;
}
// Function to print the linked list
void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
371
Chapter 65. Detect and Remove Loop in a Linked List
// Driver program to test above functions
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.head = new Node(50);
list.head.next = new Node(20);
list.head.next.next = new Node(15);
list.head.next.next.next = new Node(4);
list.head.next.next.next.next = new Node(10);
// Creating a loop for testing
head.next.next.next.next.next = head.next.next;
list.detectAndRemoveLoop(head);
System.out.println("Linked List after removing loop : ");
list.printList(head);
}
}
// This code has been contributed by Mayank Jaiswal
Python
# Python program to detect and remove loop in linked list
# Node class
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
def detectAndRemoveLoop(self):
slow_p = 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 and fast_p meet at some point then
# there is a loop
372
Chapter 65. Detect and Remove Loop in a Linked List
if slow_p == fast_p:
self.removeLoop(slow_p)
# Return 1 to indicate that loop is found
return 1
# Return 0 to indicate that there is no loop
return 0
# Function to remove loop
# loop_node --> pointer to one of the loop nodes
# head --> Pointer to the start node of the linked list
def removeLoop(self, loop_node):
ptr1 = loop_node
ptr2 = loop_node
# Count the number of nodes in loop
k = 1
while(ptr1.next != ptr2):
ptr1 = ptr1.next
k += 1
# Fix one pointer to head
ptr1 = self.head
# And the other pointer to k nodes after head
ptr2 = self.head
for i in range(k):
ptr2 = ptr2.next
# Move both pointers at the same place
# they will meet at loop starting node
while(ptr2 != ptr1):
ptr1 = ptr1.next
ptr2 = ptr2.next
# Get pointer to the last node
ptr2 = ptr2.next
while(ptr2.next != ptr1):
ptr2 = ptr2.next
# Set the next node of the loop ending node
# to fix the loop
ptr2.next = None
# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
373
Chapter 65. Detect and Remove Loop in a Linked List
new_node.next = self.head
self.head = new_node
# Utility function to prit the linked LinkedList
def printList(self):
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)
# Create a loop for testing
llist.head.next.next.next.next.next = llist.head.next.next
llist.detectAndRemoveLoop()
print "Linked List after removing loop"
llist.printList()
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Linked List after removing loop
50 20 15 4 10
Method 3 (Optimized Method 2: Without Counting Nodes in Loop)
We do not need to count number of nodes in Loop. After detecting the loop, if we start
slow pointer from head and move both slow and fast pointers at same speed until fast don’t
meet, they would meet at the beginning of the loop.
How does this work?
Let slow and fast meet at some point after Floyd’s Cycle finding algorithm. Below diagram
shows the situation when cycle is found.
374
Chapter 65. Detect and Remove Loop in a Linked List
We can conclude below from above diagram
Distance traveled by fast pointer = 2 * (Distance traveled
by slow pointer)
(m + n*x + k) = 2*(m + n*y + k)
Note that before meeting the point shown above, fast
was moving at twice speed.
x --> Number of complete cyclic rounds made by
fast pointer before they meet first time
y --> Number of complete cyclic rounds made by
slow pointer before they meet first time
From above equation, we can conclude below
m + k = (x-2y)*n
Which means m+k is a multiple of 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++
// C++ program to detect and remove loop
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int key;
struct Node *next;
};
Node *newNode(int key)
{
Node *temp = new Node;
temp->key = key;
temp->next = NULL;
return temp;
}
// A utility function to print a linked list
void printList(Node *head)
{
while (head != NULL)
{
cout << head->key << " ";
head = head->next;
}
cout << endl;
}
// Function to detect and remove loop
// in a linked list that may contain loop
void detectAndRemoveLoop(Node *head)
{
// If list is empty or has only one node
// without loop
if (head == NULL || head->next == NULL)
return;
Node *slow = head, *fast = head;
// Move slow and fast 1 and 2 steps
// ahead respectively.
slow = slow->next;
fast = fast->next->next;
376
Chapter 65. Detect and Remove Loop in a Linked List
// Search for loop using slow and
// fast pointers
while (fast && fast->next)
{
if (slow == fast)
break;
slow = slow->next;
fast = fast->next->next;
}
/* If loop exists */
if (slow == fast)
{
slow = head;
while (slow->next != fast->next)
{
slow = slow->next;
fast = fast->next;
}
/* since fast->next is the looping point */
fast->next = NULL; /* remove loop */
}
}
/* Driver program to test above function*/
int main()
{
Node *head = newNode(50);
head->next = head;
head->next = newNode(20);
head->next->next = newNode(15);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(10);
/* Create a loop for testing */
head->next->next->next->next->next = head->next->next;
detectAndRemoveLoop(head);
printf("Linked List after removing loop \n");
printList(head);
return 0;
}
Java
377
Chapter 65. Detect and Remove Loop in a Linked List
// Java program to detect and remove loop in linked list
class LinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
// Function that detects loop in the list
void detectAndRemoveLoop(Node node) {
// If list is empty or has only one node
// without loop
if (node == null || node.next == null)
return;
Node slow = node, fast = node;
// Move slow and fast 1 and 2 steps
// ahead respectively.
slow = slow.next;
fast = fast.next.next;
// Search for loop using slow and fast pointers
while (fast != null && fast.next != null) {
if (slow == fast)
break;
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
/* since fast->next is the looping point */
fast.next = null; /* remove loop */
}
}
// Function to print the linked list
void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
// Driver program to test above functions
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.head = new Node(50);
list.head.next = new Node(20);
list.head.next.next = new Node(15);
list.head.next.next.next = new Node(4);
list.head.next.next.next.next = new Node(10);
// Creating a loop for testing
head.next.next.next.next.next = head.next.next;
list.detectAndRemoveLoop(head);
System.out.println("Linked List after removing loop : ");
list.printList(head);
}
}
// This code has been contributed by Mayank Jaiswal
Python
# Python program to detect and remove loop
# Node class
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
379
Chapter 65. Detect and Remove Loop in a Linked List
def __init__(self):
self.head = None
# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def detectAndRemoveLoop(self):
if self.head is None :
return
if self.head.next is None :
return
slow = self.head
fast = self.head
# Move slow and fast 1 and 2 steps respectively
slow = slow.next
fast = fast.next.next
# Search for loop using slow and fast pointers
while (fast is not None):
if fast.next is None:
break
if slow == fast :
break
slow = slow.next
fast = fast.next.next
# if loop exists
if slow == fast :
slow = self.head
while (slow.next != fast.next):
slow = slow.next
fast = fast.next
# Sinc fast.next is the looping point
fast.next = None # Remove loop
# Utility function to print the linked LinkedList
def printList(self):
temp = self.head
while(temp):
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)
#Create a loop for testing
llist.head.next.next.next.next.next = llist.head.next.next
llist.detectAndRemoveLoop()
print "Linked List after removing loop"
llist.printList()
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Linked List after removing loop
50 20 15 4 10
Method 4 Hashing: Hash the address of the linked list nodes
We can hash the addresses of the linked list nodes in an unordered map and just check if
the element already exists in the map. If it exists, we have reached a node which already
exists by a cycle, hence we need to make the last node’s next pointer NULL.
C++
// C++ program to detect and remove loop
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int key;
struct Node *next;
};
Node *newNode(int key)
{
Node *temp = new Node;
temp->key = key;
381
Chapter 65. Detect and Remove Loop in a Linked List
temp->next = NULL;
return temp;
}
// A utility function to print a linked list
void printList(Node *head)
{
while (head != NULL)
{
cout << head->key << " ";
head = head->next;
}
cout << endl;
}
// Function to detect and remove loop
// in a linked list that may contain loop
void hashAndRemove(Node *head)
{
//hash map to hash addresses of the linked list nodes
unordered_map<Node*, int> node_map;
//pointer to last node
Node* last = NULL;
while(head!=NULL){
//if node not present in the map, insert it in the map
if(node_map.find(head) == node_map.end()){
node_map[head]++;
last = head;
head = head->next;
}
//if present, it is a cycle, make the last node's next pointer NULL
else{
last->next = NULL;
head = head->next;
}
}
}
/* Driver program to test above function*/
int main()
{
Node *head = newNode(50);
head->next = head;
head->next = newNode(20);
head->next->next = newNode(15);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(10);
/* Create a loop for testing */
382
Chapter 65. Detect and Remove Loop in a Linked List
head->next->next->next->next->next = head->next->next;
//printList(head);
hashAndRemove(head);
printf("Linked List after removing loop \n");
printList(head);
return 0;
}
We Thank Shubham Agrawal for suggesting this solution.
Thanks to Gaurav Ahirwar for suggesting above solution.
Improved By : Shubham Agrawal 8
Source
https://www.geeksforgeeks.org/detect-and-remove-loop-in-a-linked-list/
383
Chapter 66
Detect loop in a linked list
Detect loop in a linked list - GeeksforGeeks
Given a linked list, check if the the linked list has loop or not. Below diagram shows a
linked list with a loop.
Following are different ways of doing this
Use Hashing:
Traverse the list one by one and keep putting the node addresses in a Hash Table. At any
point, if NULL is reached then return false and if next of current node points to any of the
previously stored nodes in Hash then return true.
C++
// C++ program to detect loop in a linked list
#include<bits/stdc++.h>
using namespace std;
/* Link list node */
struct Node
{
int data;
struct Node* next;
384
Chapter 66. Detect loop in a linked list
};
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node = new Node;
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
// Returns true if there is a loop in linked list
// else returns false.
bool detectLoop(struct Node *h)
{
unordered_set<Node *> s;
while (h != NULL)
{
// If this node is already present
// in hashmap it means there is a cycle
// (Because you we encountering the
// node for the second time).
if (s.find(h) != s.end())
return true;
// If we are seeing the node for
// the first time, insert it in hash
s.insert(h);
h = h->next;
}
return false;
}
/* Drier program to test above function*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
push(&head, 20);
385
Chapter 66. Detect loop in a linked list
push(&head, 4);
push(&head, 15);
push(&head, 10);
/* Create a loop for testing */
head->next->next->next->next = head;
if (detectLoop(head))
cout << "Loop found";
else
cout << "No Loop";
return 0;
}
// This code is contributed by Geetanjali
Java
// Java program to detect loop in a linked list
import java.util.*;
public class LinkedList {
static Node head; // head of list
/* Linked list Node*/
static class Node
{
int data;
Node next;
Node(int d) {data = d; next = null; }
}
/* Inserts a new Node at front of the list. */
static public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
// Returns true if there is a loop in linked
386
Chapter 66. Detect loop in a linked list
// list else returns false.
static boolean detectLoop(Node h)
{
HashSet<Node> s = new HashSet<Node>();
while (h != null)
{
// If we have already has this node
// in hashmap it means their is a cycle
// (Because you we encountering the
// node second time).
if (s.contains(h))
return true;
// If we are seeing the node for
// the first time, insert it in hash
s.add(h);
h = h.next;
}
return false;
}
/* Driver program to test above function */
public static void main(String[] args)
{
LinkedList llist = new LinkedList();
llist.push(20);
llist.push(4);
llist.push(15);
llist.push(10);
/*Create loop for testing */
llist.head.next.next.next.next = llist.head;
if (detectLoop(head))
System.out.println("Loop found");
else
System.out.println("No Loop");
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
387
Chapter 66. Detect loop in a linked list
# Python program to detect loop
# in the linked list
# Node class
class Node:
# Constructor to initialize
# the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to insert a new
# node at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Utility function to prit
# the linked LinkedList
def printList(self):
temp = self.head
while(temp):
print (temp.data,end=" ")
temp = temp.next
def detectLoop(self):
s = set()
temp=self.head
while (temp):
# If we have already has
# this node in hashmap it
# means their is a cycle
# (Because you we encountering
# the node second time).
if (temp in s):
return True
# If we are seeing the node for
388
Chapter 66. Detect loop in a linked list
# the first time, insert it in hash
s.add(temp)
temp = temp.next
return False
# Driver program for testing
llist = LinkedList()
llist.push(20)
llist.push(4)
llist.push(15)
llist.push(10)
# Create a loop for testing
llist.head.next.next.next.next = llist.head;
if( llist.detectLoop()):
print ("Loop found")
else :
print ("No Loop ")
# This code is contributed by Gitanjali.
Output :
Loop Found
Mark Visited Nodes:
This solution requires modifications to basic linked list data structure. Have a visited flag
with each node. Traverse the linked list and keep marking visited nodes. If you see a
visited node again then there is a loop. This solution works in O(n) but requires additional
information with each node.
A variation of this solution that doesn’t require modification to basic data structure can be
implemented using hash. Just store the addresses of visited nodes in a hash and if you see
an address that already exists in hash then there is a loop.
Floyd’s Cycle-Finding Algorithm:
This is the fastest method. Traverse linked list using two pointers. Move one pointer by
one and other pointer by two. If these pointers meet at same node then there is a loop. If
pointers do not meet then linked list doesn’t have loop.
Implementation of Floyd’s Cycle-Finding Algorithm:
C/C++
389
Chapter 66. Detect loop in a linked list
// C program to detect loop in a linked list
#include<stdio.h>
#include<stdlib.h>
/* Link list node */
struct Node
{
int data;
struct Node* next;
};
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
int detectloop(struct Node *list)
{
struct Node *slow_p = list, *fast_p = list;
while (slow_p && fast_p && fast_p->next )
{
slow_p = slow_p->next;
fast_p = fast_p->next->next;
if (slow_p == fast_p)
{
printf("Found Loop");
return 1;
}
}
return 0;
}
/* Drier program to test above function*/
int main()
{
/* Start with the empty list */
390
Chapter 66. Detect loop in a linked list
struct Node* head = NULL;
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 10);
/* Create a loop for testing */
head->next->next->next->next = head;
detectloop(head);
return 0;
}
Java
// Java program to detect loop in a linked list
class LinkedList
{
Node head; // head of list
/* Linked list Node*/
class Node
{
int data;
Node next;
Node(int d) {data = d; next = null; }
}
/* Inserts a new Node at front of the list. */
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
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;
}
/* Drier program to test above functions */
public static void main(String args[])
{
LinkedList llist = new LinkedList();
llist.push(20);
llist.push(4);
llist.push(15);
llist.push(10);
/*Create loop for testing */
llist.head.next.next.next.next = llist.head;
llist.detectLoop();
}
}
/* This code is contributed by Rajat Mishra. */
Python
# Python program to detect loop in the linked list
# Node class
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
392
Chapter 66. Detect loop in a linked list
new_node.next = self.head
self.head = new_node
# Utility function to prit the linked LinkedList
def printList(self):
temp = self.head
while(temp):
print temp.data,
temp = temp.next
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
# Driver program for testing
llist = LinkedList()
llist.push(20)
llist.push(4)
llist.push(15)
llist.push(10)
# Create a loop for testing
llist.head.next.next.next.next = llist.head
llist.detectLoop()
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Found loop
Time Complexity: O(n)
Auxiliary Space: O(1)
How does above algorithm work?
Please See : How does Floyd’s slow and fast pointers approach work?
References:
http://en.wikipedia.org/wiki/Cycle_detection
http://ostermiller.org/find_loop_singly_linked_list.html
Improved By : PrasadPawar, ashwinvivek
393
Chapter 66. Detect loop in a linked list
Source
https://www.geeksforgeeks.org/detect-loop-in-a-linked-list/
394
Chapter 67
Double elements and append
zeros in linked list
Double elements and append zeros in linked list - GeeksforGeeks
Given a linked list with some two adjacent repeating nodes before a zero, task is to double
the first and make next 0. After this, append all the zeros to tail.
Prerequisite: Basics of implementation of Singly Linked List
Examples :
Input : 4 -> 4 -> 0 -> 2 -> 3 -> 4 ->
3 -> 3 -> 0 -> 4 ->
Output : 8-> 2-> 3-> 4-> 6-> 4-> 0->
0-> 0-> 0->
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 ->
Input : 0 -> 4 -> 4 -> 0 -> 3 -> 3 -> 0
-> 5 -> 0 -> 0 -> 6 ->
Output : 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.
// Java code to modify linked list
import java.util.*;
// Linked List Node
class Node
{
int data;
Node next;
// Constructor
public Node(int data)
{
this.data = data;
next = null;
}
}
// Class ro perform operations
// on linked list
class GfG
{
// Recursive function to double the one of two
// elements and make next one as 0,
// which are equal before 0
public static void changeTwoBefore0(Node head)
{
// there should be atleast three elements
// to perform required operation
if (head == null || head.next == null ||
head.next.next == null)
return;
// when two continous elements
// are same
if ((head.data == head.next.data) &&
(head.next.next.data == 0))
{
int temp = head.data;
head.data = 2*temp;
head.next.data = 0;
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;
// recursive call to changeTwoBefore0
// for next element
changeTwoBefore0(head);
}
// function to append zeros at tail
public static Node appendZero(Node head)
{
if (head == null || head.next == null)
return head;
// Find tail node
Node tail = head;
while (tail.next != null)
tail = tail.next;
Node origTail = tail;
// Case when starting nodes have 0 values
// we need to change head in this case.
Node curr = head;
while (curr.next != null && curr.data == 0)
{
tail.next = curr;
tail = curr;
curr = curr.next;
}
head = curr;
// Now moving other 0s to end
Node prev = curr;
curr = curr.next;
// We check until original tail
while (curr != origTail)
{
// If current data is 0, append
// after tail and update tail.
if (curr.data == 0)
{
tail.next = curr;
tail = curr;
prev.next = curr.next;
397
Chapter 67. Double elements and append zeros in linked list
}
else
prev = curr;
// We always move current
curr = curr.next;
}
// Finally making sure that linked
// list is null terminated.
tail.next = null;
return head;
}
public static Node doubleAndAppend0(Node head)
{
// Change two same nodes before 0
changeTwoBefore0(head);
// Move all 0s to end
return appendZero(head);
}
// function to display the nodes
public static void display(Node head)
{
while (head != null)
{
System.out.print(head.data + " -> ");
head = head.next;
}
}
// Driver code
public static void main(String[] args)
{
Node head = new Node(4);
head.next = new Node(4);
head.next.next = new Node(0);
head.next.next.next = new Node(2);
head.next.next.next.next = new Node(3);
head.next.next.next.next.next = new Node(4);
head.next.next.next.next.next.next = new Node(3);
head.next.next.next.next.next.next.next = new Node(3);
head.next.next.next.next.next.next.next.next = new Node(0);
head.next.next.next.next.next.next.next.next.next = new Node(4);
398
Chapter 67. Double elements and append zeros in linked list
System.out.println("Original linked list :");
display(head);
head = doubleAndAppend0(head);
System.out.println("\nModified linked list :");
display(head);
}
}
Output :
Original linked list :
4 -> 4 -> 0 -> 2 -> 3 -> 4 -> 3 -> 3 -> 0 -> 4 ->
Modified linked list :
8 -> 2 -> 3 -> 4 -> 6 -> 4 -> 0 -> 0 -> 0 -> 0 ->
Time complexity : O(n), where n is the number of nodes of linked list.
Source
https://www.geeksforgeeks.org/double-elements-and-append-zeros-in-linked-list/
399
Chapter 68
Doubly Circular Linked List |
Set 1 (Introduction and
Insertion)
Doubly Circular Linked List | Set 1 (Introduction and Insertion) - GeeksforGeeks
Prerequisite: Doubly Linked list, Circular Linked List
Circular Doubly Linked List has properties of both doubly linked list and circular linked
list in which two consecutive elements are linked or connected by previous and next pointer
and the last node points to first node by next pointer and also the first node points to last
node by previous pointer.
Following is representation of a Circular doubly linked list node in C/C++:
// Structure of the node
struct node
{
int data;
struct node *next; // Pointer to next node
struct node *prev; // Pointer to previous node
};
400
Chapter 68. Doubly Circular Linked List | Set 1 (Introduction and Insertion)
Insertion in Circular Doubly Linked List
1. Insertion at the end of list or in an empty list
• Empty List (start = NULL): A node(Say N) is inserted with data = 5, so
previous pointer of N points to N and next pointer of N also points to N. But
now start pointer points to the first node the list.
• 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)
// Function to insert at the end
void insertEnd(struct Node** start, int value)
{
// If the list is empty, create a single node
// circular and doubly list
if (*start == NULL)
{
struct Node* new_node = new Node;
new_node->data = value;
new_node->next = new_node->prev = new_node;
*start = new_node;
return;
}
// If list is not empty
/* Find last node */
Node *last = (*start)->prev;
// Create Node dynamically
struct Node* new_node = new Node;
new_node->data = value;
// Start is going to be next of new_node
new_node->next = *start;
// Make new node previous of start
(*start)->prev = new_node;
402
Chapter 68. Doubly Circular Linked List | Set 1 (Introduction and Insertion)
// Make last preivous of new node
new_node->prev = last;
// Make new node next of old last
last->next = new_node;
}
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.
// Function to insert Node at the beginning
// of the List,
void insertBegin(struct Node** start, int value)
{
// Pointer points to last Node
struct Node *last = (*start)->prev;
struct Node* new_node = new Node;
new_node->data = value; // Inserting the data
// setting up previous and next of new node
new_node->next = *start;
new_node->prev = last;
// Update next and previous pointers of start
// and last.
last->next = (*start)->prev = new_node;
403
Chapter 68. Doubly Circular Linked List | Set 1 (Introduction and Insertion)
// Update start pointer
*start = new_node;
}
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.
// Function to insert node with value as value1.
// The new node is inserted after the node with
// with value2
void insertAfter(struct Node** start, int value1,
int value2)
{
struct Node* new_node = new Node;
new_node->data = value1; // Inserting the data
// Find node having value2 and next node of it
struct Node *temp = *start;
while (temp->data != value2)
temp = temp->next;
struct Node *next = temp->next;
// insert new_node between temp and next.
temp->next = new_node;
new_node->prev = temp;
new_node->next = next;
next->prev = 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)
// C++ program to illustrate inserting a Node in
// a Cicular Doubly Linked list in begging, end
// and middle
#include <bits/stdc++.h>
using namespace std;
// Structure of a Node
struct Node
{
int data;
struct Node *next;
struct Node *prev;
};
// Function to insert at the end
void insertEnd(struct Node** start, int value)
{
// If the list is empty, create a single node
// circular and doubly list
if (*start == NULL)
{
struct Node* new_node = new Node;
new_node->data = value;
new_node->next = new_node->prev = new_node;
*start = new_node;
return;
}
// If list is not empty
/* Find last node */
Node *last = (*start)->prev;
// Create Node dynamically
struct Node* new_node = new Node;
new_node->data = value;
// Start is going to be next of new_node
new_node->next = *start;
// Make new node previous of start
(*start)->prev = new_node;
// Make last preivous of new node
new_node->prev = last;
// Make new node next of old last
last->next = new_node;
405
Chapter 68. Doubly Circular Linked List | Set 1 (Introduction and Insertion)
// Function to insert Node at the beginning
// of the List,
void insertBegin(struct Node** start, int value)
{
// Pointer points to last Node
struct Node *last = (*start)->prev;
struct Node* new_node = new Node;
new_node->data = value; // Inserting the data
// setting up previous and next of new node
new_node->next = *start;
new_node->prev = last;
// Update next and previous pointers of start
// and last.
last->next = (*start)->prev = new_node;
// Update start pointer
*start = new_node;
}
// Function to insert node with value as value1.
// The new node is inserted after the node with
// with value2
void insertAfter(struct Node** start, int value1,
int value2)
{
struct Node* new_node = new Node;
new_node->data = value1; // Inserting the data
// Find node having value2 and next node of it
struct Node *temp = *start;
while (temp->data != value2)
temp = temp->next;
struct Node *next = temp->next;
// insert new_node between temp and next.
temp->next = new_node;
new_node->prev = temp;
new_node->next = next;
next->prev = new_node;
}
void display(struct Node* start)
406
Chapter 68. Doubly Circular Linked List | Set 1 (Introduction and Insertion)
{
struct Node *temp = start;
printf("\nTraversal in forward direction \n");
while (temp->next != start)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("%d ", temp->data);
printf("\nTraversal in reverse direction \n");
Node *last = start->prev;
temp = last;
while (temp->prev != last)
{
printf("%d ", temp->data);
temp = temp->prev;
}
printf("%d ", temp->data);
}
/* Driver program to test above functions*/
int main()
{
/* Start with the empty list */
struct Node* start = NULL;
// Insert 5. So linked list becomes 5->NULL
insertEnd(&start, 5);
// Insert 4 at the beginning. So linked
// list becomes 4->5
insertBegin(&start, 4);
// Insert 7 at the end. So linked list
// becomes 4->5->7
insertEnd(&start, 7);
// Insert 8 at the end. So linked list
// becomes 4->5->7->8
insertEnd(&start, 8);
// Insert 6, after 5. So linked list
// becomes 4->5->6->7->8
insertAfter(&start, 6, 5);
printf("Created circular doubly linked list is: ");
407
Chapter 68. Doubly Circular Linked List | Set 1 (Introduction and Insertion)
display(start);
return 0;
}
Output:
Created circular doubly linked list is:
Traversal in forward direction
4 5 6 7 8
Traversal in reverse direction
8 7 6 5 4
Following are advantages and disadvantages of circular doubly linked list:
Advantages:
• 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
• It takes slightly extra memory in each node to accommodate previous pointer.
• Lots of pointers involved while implementing or doing operations on a list. So, pointers
should be handled carefully otherwise data of the list may get lost.
Applications of Circular doubly linked list
• Managing songs playlist in media player applications.
• Managing shopping cart in online shopping.
Source
https://www.geeksforgeeks.org/doubly-circular-linked-list-set-1-introduction-and-insertion/
408
Chapter 69
Doubly Circular Linked List |
Set 2 (Deletion)
Doubly Circular Linked List | Set 2 (Deletion) - GeeksforGeeks
We have discussed doubly circular linked list introduction and its insertion.
Let us formulate the problem statement to understand the deletion process. Given a ‘key’,
delete the first occurrence of this key in circular doubly linked list.
Algorithm
Case 1: Empty List(start = NULL)
• If the list is empty, simply return.
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):
// C++ program to delete a given key from
// circular doubly linked list.
#include<bits/stdc++.h>
using namespace std;
// Structure of a Node
411
Chapter 69. Doubly Circular Linked List | Set 2 (Deletion)
struct Node
{
int data;
struct Node *next;
struct Node *prev;
};
// Function to insert node in the list
void insert(struct Node** start, int value)
{
// If the list is empty, create a single node
// circular and doubly list
if (*start == NULL)
{
struct Node* new_node = new Node;
new_node->data = value;
new_node->next = new_node->prev = new_node;
*start = new_node;
return;
}
// If list is not empty
/* Find last node */
Node *last = (*start)->prev;
// Create Node dynamically
struct Node* new_node = new Node;
new_node->data = value;
// Start is going to be next of new_node
new_node->next = *start;
// Make new node previous of start
(*start)->prev = new_node;
// Make last preivous of new node
new_node->prev = last;
// Make new node next of old last
last->next = new_node;
}
// Function to delete a given node from the list
void deleteNode(struct Node **start, int key)
{
// If list is empty
if (*start == NULL)
412
Chapter 69. Doubly Circular Linked List | Set 2 (Deletion)
return;
// Find the required node
// Declare two pointers and initialize them
struct Node *curr = *start, *prev_1 = NULL;
while (curr -> data != key)
{
// If node is not present in the list
if (curr->next == *start)
{
printf("\nList doesn't have node with value = %d", key);
return;
}
prev_1 = curr;
curr = curr -> next;
}
// Check if node is the only node in list
if (curr -> next == *start && prev_1 == NULL)
{
(*start) = NULL;
free(curr);
return;
}
// If list has more than one node,
// check if it is the first node
if (curr == *start)
{
// Move prev_1 to last node
prev_1 = (*start) -> prev;
// Move start ahead
*start = (*start) -> next;
// Adjust the pointers of prev_1 and start node
prev_1 -> next = *start;
(*start) -> prev = prev_1;
free(curr);
}
// check if it is the last node
else if (curr->next == *start)
{
// Adjust the pointers of prev_1 and start node
prev_1 -> next = *start;
(*start) -> prev = prev_1;
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;
// Adjust the pointers of prev_1 and temp node
prev_1 -> next = temp;
temp -> prev = prev_1;
free(curr);
}
}
// Fuction to display list elements
void display(struct Node* start)
{
struct Node *temp = start;
while (temp->next != start)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("%d ", temp->data);
}
// Driver program to test above functions
int main()
{
// Start with the empty list
struct Node *start = NULL;
// Created linked list will be 4->5->6->7->8
insert(&start, 4);
insert(&start, 5);
insert(&start, 6);
insert(&start, 7);
insert(&start, 8);
printf("List Before Deletion: ");
display(start);
// Delete the node which is not present in list
deleteNode(&start, 9);
printf("\nList After Deletion: ");
display(start);
414
Chapter 69. Doubly Circular Linked List | Set 2 (Deletion)
// Delete the first node
deleteNode(&start, 4);
printf("\nList After Deleting %d: ", 4);
display(start);
// Delete the last node
deleteNode(&start, 8);
printf("\nList After Deleting %d: ", 8);
display(start);
// Delete the middle node
deleteNode(&start, 6);
printf("\nList After Deleting %d: ", 6);
display(start);
return 0;
}
Output:
List Before Deletion: 4 5 6 7 8
List doesn't have node with value = 9
List After Deletion: 4 5 6 7 8
List After Deleting 4: 5 6 7 8
List After Deleting 8: 5 6 7
List After Deleting 6: 5 7
Source
https://www.geeksforgeeks.org/doubly-circular-linked-list-set-2-deletion/
415
Chapter 70
Doubly Linked List | Set 1
(Introduction and Insertion)
Doubly Linked List | Set 1 (Introduction and Insertion) - GeeksforGeeks
We strongly recommend to refer following post as a prerequisite of this post.
Linked List Introduction
Inserting a node in Singly Linked List
A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer,
together with next pointer and data which are there in singly linked list.
Following is representation of a DLL node in C language.
C
/* Node of a doubly linked list */
struct Node {
int data;
struct Node* next; // Pointer to next node in DLL
struct Node* prev; // Pointer to previous node in DLL
};
416
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
Java
// Class for Doubly Linked List
public class DLL {
Node head; // head of list
/* Doubly Linked list Node*/
class Node {
int data;
Node prev;
Node next;
// Constructor to create a new node
// next and prev is by default initialized as null
Node(int d) { data = d; }
}
}
Python3
# Node of a doubly linked list
class Node:
def __init__(self, next=None, prev=None, data=None):
self.next = next # reference to next node in DLL
self.prev = prev # reference to previous node in DLL
self.data = data
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)
3) At the end of the DLL
4) Before a given node.
1) Add a node at the front: (A 5 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 DLL. For example if the given Linked List is 10152025 and
we add an item 5 at the front, then the Linked List becomes 510152025. 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)
Following are the 5 steps to add node at the front.
C
/* Given a reference (pointer to pointer) to the head of a list
and an int, inserts a new node on the front of the list. */
void push(struct Node** head_ref, int new_data)
{
/* 1. allocate node */
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
/* 2. put in the data */
new_node->data = new_data;
/* 3. Make next of new node as head and previous as NULL */
new_node->next = (*head_ref);
418
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
new_node->prev = NULL;
/* 4. change prev of head node to new node */
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
/* 5. move the head to point to the new node */
(*head_ref) = new_node;
}
Java
// Adding a node at the front of the list
public void push(int new_data)
{
/* 1. allocate node
* 2. put in the data */
Node new_Node = new Node(new_data);
/* 3. Make next of new node as head and previous as NULL */
new_Node.next = head;
new_Node.prev = null;
/* 4. change prev of head node to new node */
if (head != null)
head.prev = new_Node;
/* 5. move the head to point to the new node */
head = new_Node;
}
Python3
# Adding a node at the front of the list
def push(self, new_data):
# 1 & 2: Allocate the Node & Put in the data
new_node = Node(data = new_data)
# 3. Make next of new node as head and previous as NULL
new_node.next = self.head
new_node.prev = None
# 4. change prev of head node to new node
if self.head is not None:
self.head.prev = new_node
419
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
# 5. move the head to point to the new node
self.head = new_node
# This code is contributed by jatinreaper
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;
}
/* 2. allocate new node */
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
/* 3. put in the data */
new_node->data = new_data;
420
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
/* 4. Make next of new node as next of prev_node */
new_node->next = prev_node->next;
/* 5. Make the next of prev_node as new_node */
prev_node->next = new_node;
/* 6. Make prev_node as previous of new_node */
new_node->prev = prev_node;
/* 7. Change previous of new_node's next node */
if (new_node->next != NULL)
new_node->next->prev = new_node;
}
Java
/* Given a node as prev_node, insert a new node after the given node */
public void InsertAfter(Node prev_Node, int new_data)
{
/*1. check if the given prev_node is NULL */
if (prev_Node == null) {
System.out.println("The given previous node cannot be NULL ");
return;
}
/* 2. allocate node
* 3. put in the data */
Node new_node = new Node(new_data);
/* 4. Make next of new node as next of prev_node */
new_node.next = prev_Node.next;
/* 5. Make the next of prev_node as new_node */
prev_Node.next = new_node;
/* 6. Make prev_node as previous of new_node */
new_node.prev = prev_Node;
/* 7. Change previous of new_node's next node */
if (new_node.next != null)
new_node.next.prev = new_node;
}
Python3
# Given a node as prev_node, insert
421
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
# a new node after the given node
def insertAfter(self, prev_node, new_data):
# 1. check if the given prev_node is NULL
if prev_node is None:
print("This node doesn't exist in DLL")
return
#2. allocate node & 3. put in the data
new_node = Node(data = new_data)
# 4. Make next of new node as next of prev_node
new_node.next = prev_node.next
# 5. Make the next of prev_node as new_node
prev_node.next = new_node
# 6. Make prev_node as previous of new_node
new_node.prev = prev_node
# 7. Change previous of new_node's next node */
if new_node.next is not None:
new_node.next.prev = new_node
# This code is contributed by jatinreaper
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)
Following are the 7 steps to add node at the end.
C
/* Given a reference (pointer to pointer) to the head
of a DLL and an int, appends a new node at the end */
void append(struct Node** head_ref, int new_data)
{
/* 1. allocate node */
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref; /* used in step 5*/
/* 2. put in the data */
new_node->data = new_data;
/* 3. This new node is going to be the last node, so
make next of it as NULL*/
new_node->next = NULL;
/* 4. If the Linked List is empty, then make the new
node as head */
if (*head_ref == NULL) {
new_node->prev = NULL;
*head_ref = new_node;
return;
}
/* 5. Else traverse till the last node */
while (last->next != NULL)
last = last->next;
423
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
/* 6. Change the next of last node */
last->next = new_node;
/* 7. Make last node as previous of new node */
new_node->prev = last;
return;
}
Java
// Add a node at the end of the list
void append(int new_data)
{
/* 1. allocate node
* 2. put in the data */
Node new_node = new Node(new_data);
Node last = head; /* used in step 5*/
/* 3. This new node is going to be the last node, so
* make next of it as NULL*/
new_node.next = null;
/* 4. If the Linked List is empty, then make the new
* node as head */
if (head == null) {
new_node.prev = null;
head = new_node;
return;
}
/* 5. Else traverse till the last node */
while (last.next != null)
last = last.next;
/* 6. Change the next of last node */
last.next = new_node;
/* 7. Make last node as previous of new node */
new_node.prev = last;
}
Python3
# Add a node at the end of the DLL
424
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
def append(self, new_data):
# 1. allocate node 2. put in the data
new_node = Node(data = new_data)
last = self.head
# 3. This new node is going to be the
# last node, so make next of it as NULL
new_node.next = None
# 4. If the Linked List is empty, then
# make the new node as head
if self.head is None:
new_node.prev = None
self.head = new_node
return
# 5. Else traverse till the last node
while (last.next is not None):
last = last.next
# 6. Change the next of last node
last.next = new_node
# 7. Make last node as previous of new node */
new_node.prev = last
# This code is contributed by jatinreaper
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)
Below is the implementaton of the above approach:
C++
// A complete working C program to demonstrate all
// insertion before a given node
#include <stdio.h>
#include <stdlib.h>
// A linked list node
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
/* Given a reference (pointer to pointer) to the head of a list
and an int, inserts a new node on the front of the list. */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
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)
/* 2. allocate new node */
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
/* 3. put in the data */
new_node->data = new_data;
/* 4. Make prev of new node as prev of next_node */
new_node->prev = next_node->prev;
/* 5. Make the prev of next_node as new_node */
next_node->prev = new_node;
/* 6. Make next_node as next of new_node */
new_node->next = next_node;
/* 7. Change next of new_node's previous node */
if (new_node->prev != NULL)
new_node->prev->next = new_node;
}
// 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;
}
printf("\nTraversal in reverse direction \n");
while (last != NULL) {
printf(" %d ", last->data);
last = last->prev;
}
}
/* Driver program to test above functions*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
push(&head, 7);
push(&head, 1);
427
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
push(&head, 4);
// Insert 8, before 1. So linked list becomes 4->8->1->7->NULL
insertBefore(head->next, 8);
printf("Created DLL is: ");
printList(head);
getchar();
return 0;
}
Output:
Created DLL is:
Traversal in forward direction
4 8 1 7
Traversal in reverse direction
7 1 8 4
A complete working program to test above functions.
Following is complete C program to test above functions.
// A complete working C program to demonstrate all insertion methods
#include <stdio.h>
#include <stdlib.h>
// A linked list node
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
/* Given a reference (pointer to pointer) to the head of a list
and an int, inserts a new node on the front of the list. */
void push(struct Node** head_ref, int new_data)
{
/* 1. allocate node */
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
/* 2. put in the data */
new_node->data = new_data;
428
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
/* 3. Make next of new node as head and previous as NULL */
new_node->next = (*head_ref);
new_node->prev = NULL;
/* 4. change prev of head node to new node */
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
/* 5. move the head to point to the new node */
(*head_ref) = new_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;
}
/* 2. allocate new node */
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
/* 3. put in the data */
new_node->data = new_data;
/* 4. Make next of new node as next of prev_node */
new_node->next = prev_node->next;
/* 5. Make the next of prev_node as new_node */
prev_node->next = new_node;
/* 6. Make prev_node as previous of new_node */
new_node->prev = prev_node;
/* 7. Change previous of new_node's next node */
if (new_node->next != NULL)
new_node->next->prev = new_node;
}
/* Given a reference (pointer to pointer) to the head
of a DLL and an int, appends a new node at the end */
void append(struct Node** head_ref, int new_data)
{
/* 1. allocate node */
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
429
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
struct Node* last = *head_ref; /* used in step 5*/
/* 2. put in the data */
new_node->data = new_data;
/* 3. This new node is going to be the last node, so
make next of it as NULL*/
new_node->next = NULL;
/* 4. If the Linked List is empty, then make the new
node as head */
if (*head_ref == NULL) {
new_node->prev = NULL;
*head_ref = new_node;
return;
}
/* 5. Else traverse till the last node */
while (last->next != NULL)
last = last->next;
/* 6. Change the next of last node */
last->next = new_node;
/* 7. Make last node as previous of new node */
new_node->prev = last;
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;
}
printf("\nTraversal in reverse direction \n");
while (last != NULL) {
printf(" %d ", last->data);
last = last->prev;
}
}
430
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
/* Drier program to test above functions*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
// Insert 6. So linked list becomes 6->NULL
append(&head, 6);
// Insert 7 at the beginning. So linked list becomes 7->6->NULL
push(&head, 7);
// Insert 1 at the beginning. So linked list becomes 1->7->6->NULL
push(&head, 1);
// Insert 4 at the end. So linked list becomes 1->7->6->4->NULL
append(&head, 4);
// Insert 8, after 7. So linked list becomes 1->7->8->6->4->NULL
insertAfter(head->next, 8);
printf("Created DLL is: ");
printList(head);
getchar();
return 0;
}
Java
// A complete working Java program to demonstrate all
// Class for Doubly Linked List
public class DLL {
Node head; // head of list
/* Doubly Linked list Node*/
class Node {
int data;
Node prev;
Node next;
// Constructor to create a new node
// next and prev is by default initialized as null
Node(int d) { data = d; }
}
// Adding a node at the front of the list
431
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
public void push(int new_data)
{
/* 1. allocate node
* 2. put in the data */
Node new_Node = new Node(new_data);
/* 3. Make next of new node as head and previous as NULL */
new_Node.next = head;
new_Node.prev = null;
/* 4. change prev of head node to new node */
if (head != null)
head.prev = new_Node;
/* 5. move the head to point to the new node */
head = new_Node;
}
/* Given a node as prev_node, insert a new node after the given node */
public void InsertAfter(Node prev_Node, int new_data)
{
/*1. check if the given prev_node is NULL */
if (prev_Node == null) {
System.out.println("The given previous node cannot be NULL ");
return;
}
/* 2. allocate node
* 3. put in the data */
Node new_node = new Node(new_data);
/* 4. Make next of new node as next of prev_node */
new_node.next = prev_Node.next;
/* 5. Make the next of prev_node as new_node */
prev_Node.next = new_node;
/* 6. Make prev_node as previous of new_node */
new_node.prev = prev_Node;
/* 7. Change previous of new_node's next node */
if (new_node.next != null)
new_node.next.prev = new_node;
}
// Add a node at the end of the list
void append(int 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);
Node last = head; /* used in step 5*/
/* 3. This new node is going to be the last node, so
* make next of it as NULL*/
new_node.next = null;
/* 4. If the Linked List is empty, then make the new
* node as head */
if (head == null) {
new_node.prev = null;
head = new_node;
return;
}
/* 5. Else traverse till the last node */
while (last.next != null)
last = last.next;
/* 6. Change the next of last node */
last.next = new_node;
/* 7. Make last node as previous of new node */
new_node.prev = last;
}
// 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)
/* Drier program to test above functions*/
public static void main(String[] args)
{
/* Start with the empty list */
DLL dll = new DLL();
// Insert 6. So linked list becomes 6->NULL
dll.append(6);
// Insert 7 at the beginning. So linked list becomes 7->6->NULL
dll.push(7);
// Insert 1 at the beginning. So linked list becomes 1->7->6->NULL
dll.push(1);
// Insert 4 at the end. So linked list becomes 1->7->6->4->NULL
dll.append(4);
// Insert 8, after 7. So linked list becomes 1->7->8->6->4->NULL
dll.InsertAfter(dll.head.next, 8);
System.out.println("Created DLL is: ");
dll.printlist(dll.head);
}
}
// This code is contributed by Sumit Ghosh
Python
# A complete working Python program to demonstrate all
# insertion methods
# A linked list node
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
# Class to create a Doubly Linked List
class DoublyLinkedList:
# Constructor for empty Doubly Linked List
def __init__(self):
self.head = None
434
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
# Given a reference to the head of a list and an
# integer, inserts a new node on the front of list
def push(self, new_data):
# 1. Allocates node
# 2. Put the data in it
new_node = Node(new_data)
# 3. Make next of new node as head and
# previous as None (already None)
new_node.next = self.head
# 4. change prev of head node to new_node
if self.head is not None:
self.head.prev = new_node
# 5. move the head to point to the new node
self.head = new_node
# Given a node as prev_node, insert a new node after
# the given node
def insertAfter(self, prev_node, new_data):
# 1. Check if the given prev_node is None
if prev_node is None:
print "the given previous node cannot be NULL"
return
# 2. allocate new node
# 3. put in the data
new_node = Node(new_data)
# 4. Make net of new node as next of prev node
new_node.next = prev_node.next
# 5. Make prev_node as previous of new_node
prev_node.next = new_node
# 6. Make prev_node ass previous of new_node
new_node.prev = prev_node
# 7. Change previous of new_nodes's next node
if new_node.next is not None:
new_node.next.prev = new_node
# Given a reference to the head of DLL and integer,
# appends a new node at the end
435
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
def append(self, new_data):
# 1. Allocates node
# 2. Put in the data
new_node = Node(new_data)
# 3. This new node is going to be the last node,
# so make next of it as None
new_node.next = None
# 4. If the Linked List is empty, then make the
# new node as head
if self.head is None:
new_node.prev = None
self.head = new_node
return
# 5. Else traverse till the last node
last = self.head
while(last.next is not None):
last = last.next
# 6. Change the next of last node
last.next = new_node
# 7. Make last node as previous of new node
new_node.prev = last
return
# This function prints contents of linked list
# starting from the given node
def printList(self, node):
print "\nTraversal in forward direction"
while(node is not None):
print " % d" %(node.data),
last = node
node = node.next
print "\nTraversal in reverse direction"
while(last is not None):
print " % d" %(last.data),
last = last.prev
# Driver program to test above functions
# Start with empty list
436
Chapter 70. Doubly Linked List | Set 1 (Introduction and Insertion)
llist = DoublyLinkedList()
# Insert 6. So the list becomes 6->None
llist.append(6)
# Insert 7 at the beginning.
# So linked list becomes 7->6->None
llist.push(7)
# Insert 1 at the beginning.
# So linked list becomes 1->7->6->None
llist.push(1)
# Insert 4 at the end.
# So linked list becomes 1->7->6->4->None
llist.append(4)
# Insert 8, after 7.
# So linked list becomes 1->7->8->6->4->None
llist.insertAfter(llist.head.next, 8)
print "Created DLL is: ",
llist.printList(llist.head)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Created DLL is:
Traversal in forward direction
1 7 8 6 4
Traversal in reverse direction
4 6 8 7 1
Also see – Delete a node in double Link List
Please write comments if you find anything incorrect, or you want to share more information
about the topic discussed above.
Improved By : jatinreaper
Source
https://www.geeksforgeeks.org/doubly-linked-list/
437
Chapter 71
Exchange first and last nodes in
Circular Linked List
Exchange first and last nodes in Circular Linked List - GeeksforGeeks
Given a Circular linked list exchange the first and the last node. The task should be done
with only one extra node, you can not declare more than one extra node and also you are
not allowed to declare any other temporary variable.
Note: Extra node means need of a node to traverse a list.
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.
// CPP program to exchange first and
// last node in circular linked list
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *next;
};
struct Node *addToEmpty(struct Node *head, int data)
{
// This function is only for empty list
if (head != NULL)
return head;
// Creating a node dynamically.
struct Node *temp =
(struct Node*)malloc(sizeof(struct Node));
// Assigning the data.
temp -> data = data;
head = temp;
// Creating the link.
head -> next = head;
return head;
}
struct Node *addBegin(struct Node *head, int data)
{
if (head == NULL)
return addToEmpty(head, data);
struct Node *temp =
(struct Node *)malloc(sizeof(struct Node));
temp -> data = data;
temp -> next = head -> next;
head -> next = temp;
return head;
}
439
Chapter 71. Exchange first and last nodes in Circular Linked List
/* function for traversing the list */
void traverse(struct Node *head)
{
struct Node *p;
// If list is empty, return.
if (head == NULL)
{
cout << "List is empty." << endl;
return;
}
// Pointing to first Node of the list.
p = head;
// Traversing the list.
do
{
cout << p -> data << " ";
p = p -> next;
} while(p != head);
}
/* Function to exchange first and last node*/
struct Node *exchangeNodes(struct Node *head)
{
// Find pointer to previous of last node
struct Node *p = head;
while (p->next->next != head)
p = p->next;
/* Exchange first and last nodes using
head and p */
p->next->next = head->next;
head->next = p->next;
p->next = head;
head = head->next;
return head;
}
// Driven Program
int main()
{
int i;
struct Node *head = NULL;
440
Chapter 71. Exchange first and last nodes in Circular Linked List
head = addToEmpty(head, 6);
for (i = 5; i > 0; i--)
head = addBegin(head, i);
cout << "List Before: ";
traverse(head);
cout << endl;
cout << "List After: ";
head = exchangeNodes(head);
traverse(head);
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
Extract Leaves of a Binary Tree
in a Doubly Linked List
Extract Leaves of a Binary Tree in a Doubly Linked List - GeeksforGeeks
Given a Binary Tree, extract all leaves of it in a Doubly Linked List (DLL). Note that
the DLL need to be created in-place. Assume that the node structure of DLL and Binary
Tree is same, only the meaning of left and right pointers are different. In DLL, left means
previous pointer and right means next pointer.
Let the following be input binary tree
1
/ \
2 3
/ \ \
4 5 6
/ \ / \
7 8 9 10
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
// C program to extract leaves of a Binary Tree in a Doubly Linked List
#include <stdio.h>
#include <stdlib.h>
// Structure for tree and linked list
struct Node
{
int data;
struct Node *left, *right;
};
// 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;
if (root->left == NULL && root->right == NULL)
{
// This node is going to be added to doubly linked list
// of leaves, set right pointer of this node as previous
// head of DLL. We don't need to set left pointer as left
// is already NULL
root->right = *head_ref;
// Change left pointer of previous head
if (*head_ref != NULL) (*head_ref)->left = root;
// Change head of linked list
*head_ref = root;
return NULL; // Return new root
}
// Recur for right and left subtrees
root->right = extractLeafList(root->right, head_ref);
443
Chapter 72. Extract Leaves of a Binary Tree in a Doubly Linked List
root->left = extractLeafList(root->left, head_ref);
return root;
}
// Utility function for allocating node for Binary Tree.
struct Node* newNode(int data)
{
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return node;
}
// Utility function for printing tree in In-Order.
void print(struct Node *root)
{
if (root != NULL)
{
print(root->left);
printf("%d ",root->data);
print(root->right);
}
}
// Utility function for printing double linked list.
void printList(struct Node *head)
{
while (head)
{
printf("%d ", head->data);
head = head->right;
}
}
// Driver program to test above function
int main()
{
struct Node *head = NULL;
struct Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->right = newNode(6);
root->left->left->left = newNode(7);
root->left->left->right = newNode(8);
root->right->right->left = newNode(9);
444
Chapter 72. Extract Leaves of a Binary Tree in a Doubly Linked List
root->right->right->right = newNode(10);
printf("Inorder Trvaersal of given Tree is:\n");
print(root);
root = extractLeafList(root, &head);
printf("\nExtracted Double Linked list is:\n");
printList(head);
printf("\nInorder traversal of modified tree is:\n");
print(root);
return 0;
}
Java
// Java program to extract leaf nodes from binary tree
// using double linked list
// A binay tree node
class Node
{
int data;
Node left, right;
Node(int item)
{
data = item;
right = left = null;
}
}
public class BinaryTree
{
Node root;
Node head; // will point to head of DLL
Node prev; // temporary pointer
// The main fuction that links the list list to be traversed
public Node extractLeafList(Node root)
{
if (root == null)
return null;
if (root.left == null && root.right == null)
{
if (head == 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;
}
//Prints the DLL in both forward and reverse directions.
public void printDLL(Node head)
{
Node last = null;
while (head != null)
{
System.out.print(head.data + " ");
last = head;
head = head.right;
}
}
void inorder(Node node)
{
if (node == null)
return;
inorder(node.left);
System.out.print(node.data + " ");
inorder(node.right);
}
// Driver program to test above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.right = new Node(6);
446
Chapter 72. Extract Leaves of a Binary Tree in a Doubly Linked List
tree.root.left.left.left = new Node(7);
tree.root.left.left.right = new Node(8);
tree.root.right.right.left = new Node(9);
tree.root.right.right.right = new Node(10);
System.out.println("Inorder traversal of given tree is : ");
tree.inorder(tree.root);
tree.extractLeafList(tree.root);
System.out.println("");
System.out.println("Extracted double link list is : ");
tree.printDLL(tree.head);
System.out.println("");
System.out.println("Inorder traversal of modified tree is : ");
tree.inorder(tree.root);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Python
# Python program to extract leaf nodes from binary tree
# using double linked list
# A binary tree node
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# 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
if root.left is None and root.right is None:
# This node is going to be added to doubly linked
# list of leaves, set pointer of this node as
447
Chapter 72. Extract Leaves of a Binary Tree in a Doubly Linked List
# previous head of DLL. We don't need to set left
# pointer as left is already None
root.right = extractLeafList.head
# Change the left pointer of previous head
if extractLeafList.head is not None:
extractLeafList.head.left = root
# Change head of linked list
extractLeafList.head = root
return None # Return new root
# Recur for right and left subtrees
root.right = extractLeafList(root.right)
root.left = extractLeafList(root.left)
return root
# Utility function for printing tree in InOrder
def printInorder(root):
if root is not None:
printInorder(root.left)
print root.data,
printInorder(root.right)
def printList(head):
while(head):
if head.data is not None:
print head.data,
head = head.right
# Driver program to test above function
extractLeafList.head = Node(None)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.right = Node(6)
root.left.left.left = Node(7)
root.left.left.right = Node(8)
root.right.right.left = Node(9)
root.right.right.right = Node(10)
print "Inorder traversal of given tree is:"
printInorder(root)
448
Chapter 72. Extract Leaves of a Binary Tree in a Doubly Linked List
root = extractLeafList(root)
print "\nExtract Double Linked List is:"
printList(extractLeafList.head)
print "\nInorder traversal of modified tree is:"
printInorder(root)
Output:
Inorder Trvaersal of given Tree is:
7 4 8 2 5 1 3 9 6 10
Extracted Double Linked list is:
7 8 5 9 10
Inorder traversal of modified tree is:
4 2 1 3 6
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
Find Length of a Linked List
(Iterative and Recursive)
Find Length of a Linked List (Iterative and Recursive) - GeeksforGeeks
Write a C function to count number of nodes in a given singly linked list.
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++
// Iterative C program to find length or count of nodes in a linked list
#include<stdio.h>
#include<stdlib.h>
/* Link list node */
struct Node
{
int data;
struct Node* next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Counts no. of nodes in linked list */
int getCount(struct Node* head)
{
int count = 0; // Initialize count
struct Node* current = head; // Initialize current
while (current != NULL)
{
count++;
current = current->next;
}
return count;
}
/* Drier program to test count function*/
int main()
{
451
Chapter 73. Find Length of a Linked List (Iterative and Recursive)
/* Start with the empty list */
struct Node* head = NULL;
/* Use push() to construct below list
1->2->1->3->1 */
push(&head, 1);
push(&head, 3);
push(&head, 1);
push(&head, 2);
push(&head, 1);
/* Check the count function */
printf("count of nodes is %d", getCount(head));
return 0;
}
Java
// Java program to count number of nodes in a linked list
/* Linked list Node*/
class Node
{
int data;
Node next;
Node(int d) { data = d; next = null; }
}
// Linked List class
class LinkedList
{
Node head; // head of list
/* Inserts a new Node at front of the list. */
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
/* Returns count of nodes in linked list */
452
Chapter 73. Find Length of a Linked List (Iterative and Recursive)
public int getCount()
{
Node temp = head;
int count = 0;
while (temp != null)
{
count++;
temp = temp.next;
}
return count;
}
/* Drier program to test above functions. Ideally
this function should be in a separate user class.
It is kept here to keep code compact */
public static void main(String[] args)
{
/* Start with the empty list */
LinkedList llist = new LinkedList();
llist.push(1);
llist.push(3);
llist.push(1);
llist.push(2);
llist.push(1);
System.out.println("Count of nodes is " +
llist.getCount());
}
}
Python
# A complete working Python program to find length of a
# Linked List iteratively
# 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
# Linked List class contains a Node object
class LinkedList:
# Function to initialize head
def __init__(self):
453
Chapter 73. Find Length of a Linked List (Iterative and Recursive)
self.head = None
# This function is in LinkedList class. It inserts
# a new node at the beginning of Linked List.
def push(self, new_data):
# 1 & 2: Allocate the Node &
# Put in the data
new_node = 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
# This function counts number of nodes in Linked List
# iteratively, given 'node' as starting node.
def getCount(self):
temp = self.head # Initialise temp
count = 0 # Initialise count
# Loop while end of linked list is not reached
while (temp):
count += 1
temp = temp.next
return count
# Code execution starts here
if __name__=='__main__':
llist = LinkedList()
llist.push(1)
llist.push(3)
llist.push(1)
llist.push(2)
llist.push(1)
print ("Count of nodes is :",llist.getCount())
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++
// Recursive C program to find length or count of nodes in a linked list
#include<stdio.h>
#include<stdlib.h>
/* Link list node */
struct Node
{
int data;
struct Node* next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Counts the no. of occurences of a node
(search_for) in a linked list (head)*/
int getCount(struct Node* head)
{
// Base case
if (head == NULL)
return 0;
455
Chapter 73. Find Length of a Linked List (Iterative and Recursive)
// count is 1 + count of remaining list
return 1 + getCount(head->next);
}
/* Drier program to test count function*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
/* Use push() to construct below list
1->2->1->3->1 */
push(&head, 1);
push(&head, 3);
push(&head, 1);
push(&head, 2);
push(&head, 1);
/* Check the count function */
printf("count of nodes is %d", getCount(head));
return 0;
}
Java
// Recursive Java program to count number of nodes in
// a linked list
/* Linked list Node*/
class Node
{
int data;
Node next;
Node(int d) { data = d; next = null; }
}
// Linked List class
class LinkedList
{
Node head; // head of list
/* Inserts a new Node at front of the list. */
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
456
Chapter 73. Find Length of a Linked List (Iterative and Recursive)
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
/* Returns count of nodes in linked list */
public int getCountRec(Node node)
{
// Base case
if (node == null)
return 0;
// Count is this node plus rest of the list
return 1 + getCountRec(node.next);
}
/* Wrapper over getCountRec() */
public int getCount()
{
return getCountRec(head);
}
/* Drier program to test above functions. Ideally
this function should be in a separate user class.
It is kept here to keep code compact */
public static void main(String[] args)
{
/* Start with the empty list */
LinkedList llist = new LinkedList();
llist.push(1);
llist.push(3);
llist.push(1);
llist.push(2);
llist.push(1);
System.out.println("Count of nodes is " +
llist.getCount());
}
}
Python
# A complete working Python program to find length of a
# Linked List recursively
# 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
# Linked List class contains a Node object
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# This function is in LinkedList class. It inserts
# a new node at the beginning of Linked List.
def push(self, new_data):
# 1 & 2: Allocate the Node &
# Put in the data
new_node = 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
# This function counts number of nodes in Linked List
# recursively, given 'node' as starting node.
def getCountRec(self, node):
if (not node): # Base case
return 0
else:
return 1 + self.getCountRec(node.next)
# A wrapper over getCountRec()
def getCount(self):
return self.getCountRec(self.head)
# Code execution starts here
if __name__=='__main__':
llist = LinkedList()
llist.push(1)
llist.push(3)
llist.push(1)
llist.push(2)
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
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++
// C/C++ program to find a triplet from three linked lists with
460
Chapter 74. Find a triplet from three linked lists with sum equal to a given number
// sum equal to a given number
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
/* Link list node */
struct Node
{
int data;
struct Node* next;
};
/* A utility function to insert a node at the beginning of a
linked list*/
void push (struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* A function to chech if there are three elements in a, b
and c whose sum is equal to givenNumber. The function
assumes that the list b is sorted in ascending order
and c is sorted in descending order. */
bool isSumSorted(struct Node *headA, struct Node *headB,
struct Node *headC, int givenNumber)
{
struct Node *a = headA;
// Traverse through all nodes of a
while (a != NULL)
{
struct Node *b = headB;
struct Node *c = headC;
// For every node of list a, prick two nodes
// from lists b abd c
while (b != NULL && c != NULL)
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;
}
// If sum of this triplet is smaller, look for
// greater values in b
else if (sum < givenNumber)
b = b->next;
else // If sum is greater, look for smaller values in c
c = c->next;
}
a = a->next; // Move ahead in list a
}
printf ("No such triplet");
return false;
}
/* Drier program to test above function*/
int main()
{
/* Start with the empty list */
struct Node* headA = NULL;
struct Node* headB = NULL;
struct Node* headC = NULL;
/*create a linked list 'a' 10->15->5->20 */
push (&headA, 20);
push (&headA, 4);
push (&headA, 15);
push (&headA, 10);
/*create a sorted linked list 'b' 2->4->9->10 */
push (&headB, 10);
push (&headB, 9);
push (&headB, 4);
push (&headB, 2);
/*create another sorted linked list 'c' 8->4->2->1 */
push (&headC, 1);
462
Chapter 74. Find a triplet from three linked lists with sum equal to a given number
push (&headC, 2);
push (&headC, 4);
push (&headC, 8);
int givenNumber = 25;
isSumSorted (headA, headB, headC, givenNumber);
return 0;
}
Java
// Java program to find a triplet from three linked lists with
// sum equal to a given number
class LinkedList
{
Node head; // head of list
/* Linked list Node*/
class Node
{
int data;
Node next;
Node(int d) {data = d; next = null; }
}
/* A function to chech if there are three elements in a, b
and c whose sum is equal to givenNumber. The function
assumes that the list b is sorted in ascending order and
c is sorted in descending order. */
boolean isSumSorted(LinkedList la, LinkedList lb, LinkedList lc,
int givenNumber)
{
Node a = la.head;
// Traverse all nodes of la
while (a != null)
{
Node b = lb.head;
Node c = lc.head;
// for every node in la pick 2 nodes from lb and lc
while (b != null && c!=null)
{
int sum = a.data + b.data + c.data;
if (sum == givenNumber)
{
463
Chapter 74. Find a triplet from three linked lists with sum equal to a given number
System.out.println("Triplet found " + a.data +
" " + b.data + " " + c.data);
return true;
}
// If sum is smaller then look for greater value of b
else if (sum < givenNumber)
b = b.next;
else
c = c.next;
}
a = a.next;
}
System.out.println("No Triplet found");
return false;
}
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
/* Drier program to test above functions */
public static void main(String args[])
{
LinkedList llist1 = new LinkedList();
LinkedList llist2 = new LinkedList();
LinkedList llist3 = new LinkedList();
/* Create Linked List llist1 100->15->5->20 */
llist1.push(20);
llist1.push(5);
llist1.push(15);
llist1.push(100);
464
Chapter 74. Find a triplet from three linked lists with sum equal to a given number
/*create a sorted linked list 'b' 2->4->9->10 */
llist2.push(10);
llist2.push(9);
llist2.push(4);
llist2.push(2);
/*create another sorted linked list 'c' 8->4->2->1 */
llist3.push(1);
llist3.push(2);
llist3.push(4);
llist3.push(8);
int givenNumber = 25;
llist1.isSumSorted(llist1,llist2,llist3,givenNumber);
}
} /* This code is contributed by Rajat Mishra */
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
Find common elements in three
linked lists
Find common elements in three linked lists - GeeksforGeeks
Given three linked lists, find all common element among the three linked lists.
Examples:
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.
// C++ program to find common element
// in three unsorted linked list
#include <bits/stdc++.h>
#define max 1000000
using namespace std;
/* Link list node */
struct Node {
int data;
struct Node* next;
};
/* A utility function to insert a node at the
beginning of a linked list */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node =
(struct Node *)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
467
Chapter 75. Find common elements in three linked lists
/* print the common element in between
given three linked list*/
void Common(struct Node* head1,
struct Node* head2, struct Node* head3)
{
// Creating empty hash table;
unordered_map<int, int> hash;
struct Node* p = head1;
while (p != NULL) {
// set frequency by 1
hash[p->data] = 1;
p = p->next;
}
struct Node* q = head2;
while (q != NULL) {
// if the element is already exist in the
// linked list set its frequency 2
if (hash.find(q->data) != hash.end())
hash[q->data] = 2;
q = q->next;
}
struct Node* r = head3;
while (r != NULL) {
if (hash.find(r->data) != hash.end() &&
hash[r->data] == 2)
// if the element frquancy is 2 it means
// its present in both the first and second
// linked list set its frquancy 3
hash[r->data] = 3;
r = r->next;
}
for (auto x : hash) {
// if current frequency is 3 its means
// element is common in all the given
// linked list
if (x.second == 3)
468
Chapter 75. Find common elements in three linked lists
cout << x.first << " ";
}
}
// 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);
Common(head1, head2, head3);
return 0;
}
Output:
10 15 20
Time Complexity : O(m + n + p)
Source
https://www.geeksforgeeks.org/find-common-elements-in-three-linked-lists/
469
Chapter 76
Find first node of loop in a
linked list
Find first node of loop in a linked list - GeeksforGeeks
Write a function findFirstLoopNode() that checks whether a given Linked List contains loop.
If loop is present then it returns point to first node of loop. Else it returns NULL.
Example :
Input : Head of bellow linked list
Output : Pointer to node 2
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.
// C++ program to return first node of loop.
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
struct Node* next;
};
Node* newNode(int key)
{
470
Chapter 76. Find first node of loop in a linked list
Node* temp = new Node;
temp->key = key;
temp->next = NULL;
return temp;
}
// A utility function to print a linked list
void printList(Node* head)
{
while (head != NULL) {
cout << head->key << " ";
head = head->next;
}
cout << endl;
}
// Function to detect and remove loop
// in a linked list that may contain loop
Node* detectAndRemoveLoop(Node* head)
{
// If list is empty or has only one node
// without loop
if (head == NULL || head->next == NULL)
return NULL;
Node *slow = head, *fast = head;
// Move slow and fast 1 and 2 steps
// ahead respectively.
slow = slow->next;
fast = fast->next->next;
// Search for loop using slow and
// fast pointers
while (fast && fast->next) {
if (slow == fast)
break;
slow = slow->next;
fast = fast->next->next;
}
// If loop does not exist
if (slow != fast)
return NULL;
// If loop exists. Start slow from
// head and fast from meeting point.
slow = head;
471
Chapter 76. Find first node of loop in a linked list
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}
return slow;
}
/* Driver program to test above function*/
int main()
{
Node* head = newNode(50);
head->next = newNode(20);
head->next->next = newNode(15);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(10);
/* Create a loop for testing */
head->next->next->next->next->next = head->next->next;
Node* res = detectAndRemoveLoop(head);
if (res == NULL)
cout << "Loop does not exist";
else
cout << "Loop starting node is " << res->key;
return 0;
}
Output:
Loop starting node is 15
How does this approach work?
Let slow and fast meet at some point after Floyd’s Cycle finding algorithm. Below diagram
shows the situation when cycle is found.
472
Chapter 76. Find first node of loop in a linked list
We can conclude below from above diagram
Distance traveled by fast pointer = 2 * (Distance traveled
by slow pointer)
(m + n*x + k) = 2*(m + n*y + k)
Note that before meeting the point shown above, fast
was moving at twice speed.
x --> Number of complete cyclic rounds made by
fast pointer before they meet first time
y --> Number of complete cyclic rounds made by
slow pointer before they meet first time
From above equation, we can conclude below
m + k = (x-2y)*n
Which means m+k is a multiple of 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
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:
Input : List is 1->2->3->4->5->6->7
K= 2
Output : 2
Input : list is 7->8->9->10->11->12
K = 3
Output : 7
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:
// CPP program to find kth node from middle
// towards Head of the Linked List
#include <bits/stdc++.h>
using namespace std;
475
Chapter 77. Find kth node from Middle towards Head of a Linked List
// Linked list node
struct Node {
int data;
struct Node* next;
};
/* Given a reference (pointer to
pointer) to the head of a list
and an int, push a new node on
the front of the list. */
void push(struct Node** head_ref,
int new_data)
{
struct Node* new_node = new Node;
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
// Function to count number of nodes
int getCount(struct Node* head)
{
int count = 0; // Initialize count
struct Node* current = head; // Initialize current
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
// Function to get the kth node from the mid
// towards begin of the linked list
int printKthfrommid(struct Node* head_ref, int k)
{
// Get the count of total number of
// nodes in the linked list
int n = getCount(head_ref);
int reqNode = ((n / 2 + 1) - k);
// If no such node exists, return -1
if (reqNode <= 0) {
return -1;
}
// Find node at position reqNode
476
Chapter 77. Find kth node from Middle towards Head of a Linked List
else {
struct Node* current = head_ref;
// the index of the
// node we're currently
// looking at
int count = 1;
while (current != NULL) {
if (count == reqNode)
return (current->data);
count++;
current = current->next;
}
}
}
// Driver code
int main()
{
// start with empty list
struct Node* head = NULL;
int k = 2;
// create linked list
// 1->2->3->4->5->6->7
push(&head, 7);
push(&head, 6);
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
cout << printKthfrommid(head, 2);
return 0;
}
Output:
Time Complexity: O(n), where n is the length of the list.
Auxiliary Space: O(1)
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
Find length of loop in linked list
Find length of loop in linked list - GeeksforGeeks
Write a function detectAndCountLoop() that checks whether a given Linked List contains
loop and if loop is present then returns count of nodes in loop. For example, loop is present
in below linked list and length of loop is 4. If loop is not present, then function should
return 0.
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 program to count number of nodes
// in loop in a linked list if loop is
// present
#include<stdio.h>
#include<stdlib.h>
/* Link list node */
struct Node
479
Chapter 78. Find length of loop in linked list
{
int data;
struct Node* next;
};
// Returns count of nodes present in loop.
int countNodes(struct Node *n)
{
int res = 1;
struct Node *temp = n;
while (temp->next != n)
{
res++;
temp = temp->next;
}
return res;
}
/* This function detects and counts loop
nodes in the list. If loop is not there
in then returns 0 */
int countNodesinLoop(struct Node *list)
{
struct Node *slow_p = list, *fast_p = list;
while (slow_p && fast_p && fast_p->next)
{
slow_p = slow_p->next;
fast_p = fast_p->next->next;
/* If slow_p and fast_p meet at some point
then there is a loop */
if (slow_p == fast_p)
return countNodes(slow_p);
}
/* Return 0 to indeciate that ther is no loop*/
return 0;
}
struct Node *newNode(int key)
{
struct Node *temp =
(struct Node*)malloc(sizeof(struct Node));
temp->data = key;
temp->next = NULL;
return temp;
}
480
Chapter 78. Find length of loop in linked list
/* Driver program to test above function*/
int main()
{
struct 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);
/* Create a loop for testing */
head->next->next->next->next->next = head->next;
printf("%d \n", countNodesinLoop(head));
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
Find middle of singly linked list
Recursively
Find middle of singly linked list Recursively - GeeksforGeeks
Given a singly linked list and the task is to find middle of linked list.
Examples:
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.
// C++ program for Recursive approach to find
// middle of singly linked list
#include <iostream>
using namespace std;
// Tree Node Structure
struct Node
{
int data;
struct Node* next;
};
482
Chapter 79. Find middle of singly linked list Recursively
// Create new Node
Node* newLNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->next = NULL;
return temp;
}
// Function for finding midpoint recursively
void midpoint_util(Node* head, int* n, Node** mid)
{
// If we reached end of linked list
if (head == NULL)
{
*n = (*n) / 2;
return;
}
*n = *n + 1;
midpoint_util(head->next, n, mid);
// Rolling back, decrement n by one
*n = *n - 1;
if (*n == 0)
{
// Final answer
*mid = head;
}
}
Node* midpoint(Node* head)
{
Node* mid = NULL;
int n = 1;
midpoint_util(head, &n, &mid);
return mid;
}
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
Find modular node in a linked
list
Find modular node in a linked list - GeeksforGeeks
Given a singly linked list and a number k, find the last node whose n%k == 0, where n is
the number of nodes in the list.
Examples:
Input : list = 1->2->3->4->5->6->7
k = 3
Output : 6
Input : list = 3->7->1->9->8
k = 2
Output : 9
1. Take a pointer modularNode and initialize it with NULL. Traverse the linked list.
2. For every i%k=0, update modularNode.
C++
// C++ program to find modular node in a linked list
#include <bits/stdc++.h>
/* Linked list node */
struct Node {
int data;
Node* next;
};
485
Chapter 80. Find modular node in a linked list
/* Function to create a new node with given data */
Node* newNode(int data)
{
Node* new_node = new Node;
new_node->data = data;
new_node->next = NULL;
return new_node;
}
/* Function to find modular node in the linked list */
Node* modularNode(Node* head, int k)
{
// Corner cases
if (k <= 0 || head == NULL)
return NULL;
// Traverse the given list
int i = 1;
Node* modularNode = NULL;
for (Node* temp = head; temp != NULL; temp = temp->next) {
if (i % k == 0)
modularNode = temp;
i++;
}
return modularNode;
}
/* Driver program to test above function */
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);
int k = 2;
Node* answer = modularNode(head, k);
printf("\nModular node is ");
if (answer != NULL)
printf("%d\n", answer->data);
else
printf("null\n");
return 0;
}
Java
486
Chapter 80. Find modular node in a linked list
// A Java program to find modular node in a linked list
public class GFG
{
// A Linkedlist node
static class Node{
int data;
Node next;
Node(int data){
this.data = data;
}
}
// Function to find modular node in the linked list
static Node modularNode(Node head, int k)
{
// Corner cases
if (k <= 0 || head == null)
return null;
// Traverse the given list
int i = 1;
Node modularNode = null;
for (Node temp = head; temp != null; temp = temp.next) {
if (i % k == 0)
modularNode = temp;
i++;
}
return modularNode;
}
// Driver code to test above function
public static void main(String[] args)
{
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
int k = 2;
Node answer = modularNode(head, k);
System.out.print("Modular node is ");
if (answer != null)
System.out.println(answer.data);
else
System.out.println("null");
}
}
487
Chapter 80. Find modular node in a linked list
// This code is contributed by Sumit Ghosh
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
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:
Input : head = 3-->6-->7-->8-->9-->10-->11 , x=17
Output: (6, 11), (7, 10), (8, 9)
Hint : We are allowed to modify original linked list
A simple solution for this problem is to take each element one by one and traverse the
remaining list in forward direction to find second element whose sum is equal to given value
x. Time complexity for this approach will be O(n2 ).
An efficient solution for this problem is based on ideas discussed in below articles.
Find pair in doubly linked list : We use the same algorithm that traverses linked list from
both ends.
XOR Linked list : In singly linked list, we can traverse list only in forward direction. We
use XOR concept to convert a singly linked list to doubly linked list.
Below are steps :
• 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).
// C++ program to find pair with given sum in a singly
// linked list in O(n) time and no extra space.
#include<bits/stdc++.h>
using namespace std;
/* Link list node */
struct Node
{
int data;
/* also constains XOR of next and
previous node after conversion*/
struct Node* next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void insert(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
490
Chapter 81. Find pair for given sum in a sorted singly linked without extra space
/* returns XORed value of the node addresses */
struct Node* XOR (struct Node *a, struct Node *b)
{
return (struct Node*) ((uintptr_t) (a) ^ (uintptr_t) (b));
}
// Utility function to convert singly linked list
// into XOR doubly linked list
void convert(struct Node *head)
{
// first we store address of next node in it
// then take XOR of next node and previous node
// and store it in next pointer
struct Node *next_node;
// prev node stores the address of previously
// visited node
struct Node *prev = NULL;
// traverse list and store xor of address of
// next_node and prev node in next pointer of node
while (head != NULL)
{
// address of next node
next_node = head->next;
// xor of next_node and prev node
head->next = XOR(next_node, prev);
// update previous node
prev = head;
// move head forward
head = next_node;
}
}
// function to Find pair whose sum is equal to
// given value x
void pairSum(struct Node *head, int x)
{
// initialize first
struct Node *first = head;
// next_node and prev node to calculate xor again
// and find next and prev node while moving forward
// and backward direction from both the corners
491
Chapter 81. Find pair for given sum in a sorted singly linked without extra space
struct Node *next_node = NULL, *prev = NULL;
// traverse list to initialize second pointer
// here we need to move in forward direction so to
// calculate next address we have to take xor
// with prev pointer because (a^b)^b = a
struct Node *second = head;
while (second->next != prev)
{
struct Node *temp = second;
second = XOR(second->next, prev);
prev = temp;
}
// now traverse from both the corners
next_node = NULL;
prev = NULL;
// here if we want to move forward then we must
// know the prev address to calculate next node
// and if we want to move backward then we must
// know the next_node address to calculate prev node
bool flag = false;
while (first != NULL && second != NULL &&
first != second && first != next_node)
{
if ((first->data + second->data)==x)
{
cout << "(" << first->data << ","
<< second->data << ")" << endl;
flag = true;
// move first in forward
struct Node *temp = first;
first = XOR(first->next,prev);
prev = temp;
// move second in backward
temp = second;
second = XOR(second->next, next_node);
next_node = temp;
}
else
{
if ((first->data + second->data) < x)
{
// move first in forward
492
Chapter 81. Find pair for given sum in a sorted singly linked without extra space
struct Node *temp = first;
first = XOR(first->next,prev);
prev = temp;
}
else
{
// move second in backward
struct Node *temp = second;
second = XOR(second->next, next_node);
next_node = temp;
}
}
}
if (flag == false)
cout << "No pair found" << endl;
}
// Driver program to run the case
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
int x = 17;
/* Use insert() to construct below list
3-->6-->7-->8-->9-->10-->11 */
insert(&head, 11);
insert(&head, 10);
insert(&head, 9);
insert(&head, 8);
insert(&head, 7);
insert(&head, 6);
insert(&head, 3);
// convert singly linked list into XOR doubly
// linked list
convert(head);
pairSum(head,x);
return 0;
}
Output:
(6,11) , (7,10) , (8,9)
Time complexity : O(n)
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
Find pairs with given sum in
doubly linked list
Find pairs with given sum in doubly linked list - GeeksforGeeks
Given a sorted doubly linked list of positive distinct elements, the task is to find pairs in
doubly linked list whose sum is equal to given value x, without using any extra space ?
Input : head : 1 <-> 2 <-> 4 <-> 5 <-> 6 <-> 8 <-> 9
x = 7
Output: (6, 1), (5,2)
Expected time complexity is O(n) and auxiliary space is O(1).
A simple approach for this problem is to one by one pick each node and find second
element whose sum is equal to x in the remaining list by traversing in forward direction.Time
complexity for this problem will be O(n^2) , n is total number of nodes in doubly linked
list.
An efficient solution for this problem is same as this article. Here is the algorithm :
• 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
// C++ program to find a pair with given sum x.
#include<bits/stdc++.h>
using namespace std;
// structure of node of doubly linked list
struct Node
{
int data;
struct Node *next, *prev;
};
// Function to find pair whose sum equal to given value x.
void pairSum(struct Node *head, int x)
{
// Set two pointers, first to the beginning of DLL
// and second to the end of DLL.
struct Node *first = head;
struct Node *second = head;
while (second->next != NULL)
second = second->next;
// To track if we find a pair or not
bool found = false;
// The loop terminates when either of two pointers
// become NULL, or they cross each other (second->next
// == first), or they become same (first == second)
while (first != NULL && second != NULL &&
first != second && second->next != first)
{
// pair found
if ((first->data + second->data) == x)
{
found = true;
cout << "(" << first->data<< ", "
<< second->data << ")" << endl;
// move first in forward direction
first = first->next;
// move second in backward direction
second = second->prev;
}
else
{
if ((first->data + second->data) < x)
first = first->next;
else
496
Chapter 82. Find pairs with given sum in doubly linked list
second = second->prev;
}
}
// if pair is not present
if (found == false)
cout << "No pair found";
}
// A utility function to insert a new node at the
// beginning of doubly linked list
void insert(struct Node **head, int data)
{
struct Node *temp = new Node;
temp->data = data;
temp->next = temp->prev = NULL;
if (!(*head))
(*head) = temp;
else
{
temp->next = *head;
(*head)->prev = temp;
(*head) = temp;
}
}
// 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)
Time complexity : O(n)
Auxiliary space : O(1)
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-pairs-given-sum-doubly-linked-list/
498
Chapter 83
Find smallest and largest
elements in singly linked list
Find smallest and largest elements in singly linked list - GeeksforGeeks
Given a singly linked list of n nodes and find the smallest and largest elements in linked list.
Examples:
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.
// Program to find smallest and largest
// elements in singly linked list.
#include <bits/stdc++.h>
499
Chapter 83. Find smallest and largest elements in singly linked list
using namespace std;
/* Linked list node */
struct Node {
int data;
struct Node* next;
};
// Function that returns the largest element
// from the linked list.
int largestElement(struct Node* head)
{
// Declare a max variable and initialize
// it with INT_MIN value.
// INT_MIN is integer type and its value
// is -32767 or less.
int max = INT_MIN;
// Check loop while head not equal to NULL
while (head != NULL) {
// If max is less then head->data then
// assign value of head->data to max
// otherwise node point to next node.
if (max < head->data)
max = head->data;
head = head->next;
}
return max;
}
// Function that returns smallest element
// from the linked list.
int smallestElement(struct Node* head)
{
// Declare a min variable and initialize
// it with INT_MAX value.
// INT_MAX is integer type and its value
// is 32767 or greater.
int min = INT_MAX;
// Check loop while head not equal to NULL
while (head != NULL) {
// If min is greater then head->data then
// assign value of head->data to min
// otherwise node point to next node.
if (min > head->data)
min = head->data;
500
Chapter 83. Find smallest and largest elements in singly linked list
head = head->next;
}
return min;
}
// Function that push the element in linked list.
void push(struct Node** head, int data)
{
// Allocate dynamic memory for newNode.
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
// Assign the data into newNode.
newNode->data = data;
// newNode->next assign the address of
// head node.
newNode->next = (*head);
// newNode become the headNode.
(*head) = newNode;
}
// Display linked list.
void printList(struct Node* head)
{
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
cout << "NULL" << endl;
}
// Drier program to test the functions
int main()
{
// Start with empty list
struct Node* head = NULL;
// Using push() function to construct
// singly linked list
// 17->22->13->14->15
push(&head, 15);
push(&head, 14);
push(&head, 13);
push(&head, 22);
push(&head, 17);
501
Chapter 83. Find smallest and largest elements in singly linked list
cout << "Linked list is : " << endl;
// Call printList() function to display
// the linked list.
printList(head);
cout << "Maximum element in linked list:";
// Call largestElement() function to get largest
// element in linked list.
cout << largestElement(head) << endl;
cout << "Minimum element in linked list:";
// Call smallestElement() function to get smallest
// element in linked list.
cout << smallestElement(head) << endl;
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
Find the first non-repeating
character from a stream of
characters
Find the first non-repeating character from a stream of characters - GeeksforGeeks
Given a stream of characters, find the first non-repeating character from stream. You need
to tell the first non-repeating character in O(1) time at any moment.
If we follow the first approach discussed here, then we need to store the stream so that we
can traverse it one more time to find the first non-repeating character at any moment. If
we use extended approach discussed in the same post, we need to go through the count
array every time first non-repeating element is queried. We can find the first non-repeating
character from stream at any moment without traversing any array.
The idea is to use a DLL (Doubly Linked List) to efficiently get the first non-repeating
character from a stream. The DLL contains all non-repeating characters in order, i.e., the
head of DLL contains first non-repeating character, the second node contains the second
non-repeating and so on.
We also maintain two arrays: one array is to maintain characters that are already visited
two or more times, we call it repeated[], the other array is array of pointers to linked list
nodes, we call it inDLL[]. The size of both arrays is equal to alphabet size which is typically
256.
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
• If repeated[x] is true, ignore this character (x is already repeated two or more
times in the stream)
• If repeated[x] is false and inDLL[x] is NULL (x is seen first time). Append x to
DLL and store address of new DLL node in inDLL[x].
• If repeated[x] is false and inDLL[x] is not NULL (x is seen second time). Get
DLL node of x using inDLL[x] and remove the node. Also, mark inDLL[x] as
NULL and repeated[x] as true.
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++
// A C++ program to find first non-repeating character
// from a stream of characters
#include <iostream>
#define MAX_CHAR 256
using namespace std;
// A linked list node
struct node
{
char a;
struct node *next, *prev;
};
// A utility function to append a character x at the end
// of DLL. Note that the function may change head and tail
// pointers, that is why pointers to these pointers are passed.
void appendNode(struct node **head_ref, struct node **tail_ref,
char x)
{
struct node *temp = new node;
temp->a = x;
temp->prev = temp->next = NULL;
if (*head_ref == NULL)
{
*head_ref = *tail_ref = temp;
return;
}
(*tail_ref)->next = temp;
temp->prev = *tail_ref;
*tail_ref = temp;
}
// A utility function to remove a node 'temp' fromt DLL.
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];
// repeated[x] is true if x is repeated two or more times.
// If x is not seen so far or x is seen only once. then
// repeated[x] is false
bool repeated[MAX_CHAR];
// Initialize the above two arrays
struct node *head = NULL, *tail = NULL;
for (int i = 0; i < MAX_CHAR; i++)
{
inDLL[i] = NULL;
repeated[i] = false;
}
// Let us consider following stream and see the process
char stream[] = "geeksforgeeksandgeeksquizfor";
for (int i = 0; stream[i]; i++)
{
char x = stream[i];
cout << "Reading " << x << " from stream n";
// We process this character only if it has not occurred
// or occurred only once. repeated[x] is true if x is
505
Chapter 84. Find the first non-repeating character from a stream of characters
// repeated twice or more.s
if (!repeated[x])
{
// If the character is not in DLL, then add this at
// the end of DLL.
if (inDLL[x] == NULL)
{
appendNode(&head, &tail, stream[i]);
inDLL[x] = tail;
}
else // Otherwise remove this character from DLL
{
removeNode(&head, &tail, inDLL[x]);
inDLL[x] = NULL;
repeated[x] = true; // Also mark it as repeated
}
}
// Print the current first non-repeating character from
// stream
if (head != NULL)
cout << "First non-repeating character so far is "
<< head->a << endl;
}
}
/* Driver program to test above function */
int main()
{
findFirstNonRepeating();
return 0;
}
Java
//A Java program to find first non-repeating character
//from a stream of characters
import java.util.ArrayList;
import java.util.List;
public class NonReapeatingC
{
final static int MAX_CHAR = 256;
static void findFirstNonRepeating()
{
// inDLL[x] contains pointer to a DLL node if x is present
506
Chapter 84. Find the first non-repeating character from a stream of characters
// in DLL. If x is not present, then inDLL[x] is NULL
List<Character> inDLL =new ArrayList<Character>();
// repeated[x] is true if x is repeated two or more times.
// If x is not seen so far or x is seen only once. then
// repeated[x] is false
boolean[] repeated =new boolean[MAX_CHAR];
// Let us consider following stream and see the process
String stream = "geeksforgeeksandgeeksquizfor";
for (int i=0;i < stream.length();i++)
{
char x = stream.charAt(i);
System.out.println("Reading "+ x +" from stream n");
// We process this character only if it has not occurred
// or occurred only once. repeated[x] is true if x is
// repeated twice or more.s
if(!repeated[x])
{
// If the character is not in DLL, then add this at
// the end of DLL.
if(!(inDLL.contains(x)))
{
inDLL.add(x);
}
else // Otherwise remove this character from DLL
{
inDLL.remove((Character)x);
repeated[x] = true; // Also mark it as repeated
}
}
// Print the current first non-repeating character from
// stream
if(inDLL.size() != 0)
{
System.out.print("First non-repeating character so far is ");
System.out.println(inDLL.get(0));
}
}
}
/* Driver program to test above function */
public static void main(String[] args)
{
findFirstNonRepeating();
}
507
Chapter 84. Find the first non-repeating character from a stream of characters
}
//This code is contributed by Sumit Ghosh
Python
# A Python program to find first non-repeating character from
# a stream of characters
MAX_CHAR = 256
def 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
inDLL = [] * MAX_CHAR
# repeated[x] is true if x is repeated two or more times.
# If x is not seen so far or x is seen only once. then
# repeated[x] is false
repeated = [False] * MAX_CHAR
# Let us consider following stream and see the process
stream = "geeksforgeeksandgeeksquizfor"
for i in xrange(len(stream)):
x = stream[i]
print "Reading " + x + " from stream"
# We process this character only if it has not occurred
# or occurred only once. repeated[x] is true if x is
# repeated twice or more.s
if not repeated[ord(x)]:
# If the character is not in DLL, then add this
# at the end of DLL
if not x in inDLL:
inDLL.append(x)
else:
inDLL.remove(x)
if len(inDLL) != 0:
print "First non-repeating character so far is ",
print str(inDLL[0])
# Driver program
findFirstNonRepeating()
# This code is contributed by BHAVYA JAIN
Output:
508
Chapter 84. Find the first non-repeating character from a stream of characters
Reading g from stream
First non-repeating character so far is g
Reading e from stream
First non-repeating character so far is g
Reading e from stream
First non-repeating character so far is g
Reading k from stream
First non-repeating character so far is g
Reading s from stream
First non-repeating character so far is g
Reading f from stream
First non-repeating character so far is g
Reading o from stream
First non-repeating character so far is g
Reading r from stream
First non-repeating character so far is g
Reading g from stream
First non-repeating character so far is k
Reading e from stream
First non-repeating character so far is k
Reading e from stream
First non-repeating character so far is k
Reading k from stream
First non-repeating character so far is s
Reading s from stream
First non-repeating character so far is f
Reading a from stream
First non-repeating character so far is f
Reading n from stream
First non-repeating character so far is f
Reading d from stream
First non-repeating character so far is f
Reading g from stream
First non-repeating character so far is f
Reading e from stream
First non-repeating character so far is f
Reading e from stream
First non-repeating character so far is f
Reading k from stream
First non-repeating character so far is f
Reading s from stream
First non-repeating character so far is f
Reading q from stream
First non-repeating character so far is f
Reading u from stream
First non-repeating character so far is f
Reading i from stream
First non-repeating character so far is f
509
Chapter 84. Find the first non-repeating character from a stream of characters
Reading z from stream
First non-repeating character so far is f
Reading f from stream
First non-repeating character so far is o
Reading o from stream
First non-repeating character so far is r
Reading r from stream
First non-repeating character so far is a
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
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:
Input : list = 1->2->3->4->5->6
k = 2
Output : 3
Since n = 6 and k = 2, we print (6/2)-th node
which is 3.
Input : list = 2->7->9->3->5
k = 3
Output : 7
Since n is 5 and k is 3, we print ceil(5/3)-th
node which is 2nd node, i.e., 7.
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++
// C++ program to find fractional node in a linked list
#include <bits/stdc++.h>
511
Chapter 85. Find the fractional (or n/k – th) node in linked list
/* Linked list node */
struct Node {
int data;
Node* next;
};
/* Function to create a new node with given data */
Node* newNode(int data)
{
Node* new_node = new Node;
new_node->data = data;
new_node->next = NULL;
return new_node;
}
/* Function to find fractional node in the linked list */
Node* fractionalNodes(Node* head, int k)
{
// Corner cases
if (k <= 0 || head == NULL)
return NULL;
Node* fractionalNode = NULL;
// Traverse the given list
int i = 0;
for (Node* temp = head; temp != NULL; temp = temp->next) {
// For every k nodes, we move fractionalNode one
// step ahead.
if (i % k == 0) {
// First time we see a multiple of k
if (fractionalNode == NULL)
fractionalNode = head;
else
fractionalNode = fractionalNode->next;
}
i++;
}
return fractionalNode;
}
// A utility function to print a linked list
void printList(Node* node)
{
512
Chapter 85. Find the fractional (or n/k – th) node in linked list
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
/* Driver program to test above function */
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);
int k = 2;
printf("List is ");
printList(head);
Node* answer = fractionalNodes(head, k);
printf("\nFractional node is ");
printf("%d\n", answer->data);
return 0;
}
Java
// Java program to find fractional node in
// a linked list
public class FractionalNodell
{
/* Linked list node */
static class Node{
int data;
Node next;
//Constructor
Node (int data){
this.data = data;
}
}
/* Function to find fractional node in the
linked list */
static Node fractionalNodes(Node head, int k)
{
513
Chapter 85. Find the fractional (or n/k – th) node in linked list
// Corner cases
if (k <= 0 || head == null)
return null;
Node fractionalNode = null;
// Traverse the given list
int i = 0;
for (Node temp = head; temp != null;
temp = temp.next){
// For every k nodes, we move
// fractionalNode one step ahead.
if (i % k == 0){
// First time we see a multiple of k
if (fractionalNode == null)
fractionalNode = head;
else
fractionalNode = fractionalNode.next;
}
i++;
}
return fractionalNode;
}
// A utility function to print a linked list
static void printList(Node node)
{
while (node != null)
{
System.out.print(node.data+" ");
node = node.next;
}
System.out.println();
}
/* Driver program to test above function */
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
int k =2;
System.out.print("List is ");
printList(head);
514
Chapter 85. Find the fractional (or n/k – th) node in linked list
Node answer = fractionalNodes(head, k);
System.out.println("Fractional node is "+
answer.data);
}
}
// This code is contributed by Sumit Ghosh
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
Find the largest node in Doubly
linked list
Find the largest node in Doubly linked list - GeeksforGeeks
Given a doubly linked list, find the largest node in the doubly linked list.
Examples:
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 .
/* Program to find the largest
nodes in doubly linked list */
#include <stdio.h>
#include <stdlib.h>
// Create node of the doubly linked list
struct Node {
int data;
516
Chapter 86. Find the largest node in Doubly linked list
struct Node* next;
struct Node* prev;
};
/* 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));
/* put in the data */
new_node->data = new_data;
/* since we are adding at the
begining, prev is always NULL */
new_node->prev = NULL;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* change prev of head node to new node */
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to find the largest
nodes in Doubly Linked List */
int LargestInDLL(struct Node** head_ref)
{
struct Node *max, *temp;
/* initialize two pointer temp
and max on the head node */
temp = max = *head_ref;
// traverse the whole doubly linked list
while (temp != NULL) {
/* if temp's data is greater than
max's data, then put max = temp
and return max->data */
if (temp->data > max->data)
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;
// Let us create a linked list
push(&head, 20);
push(&head, 14);
push(&head, 181);
push(&head, 100);
printf("%d", LargestInDLL(&head));
return 0;
}
Output: 181
Time Complexity: O(n)
Auxiliary Space : O(1)
Source
https://www.geeksforgeeks.org/find-largest-node-doubly-linked-list/
518
Chapter 87
Find the middle of a given
linked list in C and Java
Find the middle of a given linked list in C and Java - GeeksforGeeks
Given a singly linked list, find middle of the linked list. For example, if given linked list is
1->2->3->4->5 then output should be 3.
If there are even nodes, then there would be two middle nodes, we need to print second
middle element. For example, if given linked list is 1->2->3->4->5->6 then output should
be 4.
Method 1:
Traverse the whole linked list and count the no. of nodes. Now traverse the list again till
count/2 and return the node at count/2.
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>
/* Link list node */
struct Node
{
int data;
struct Node* next;
};
/* Function to get the middle of the linked list*/
void printMiddle(struct Node *head)
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);
}
}
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
// A utility function to print a given linked list
void printList(struct Node *ptr)
{
while (ptr != NULL)
{
printf("%d->", ptr->data);
ptr = ptr->next;
}
printf("NULL\n");
}
/* Drier program to test above function*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
int i;
520
Chapter 87. Find the middle of a given linked list in C and Java
for (i=5; i>0; i--)
{
push(&head, i);
printList(head);
printMiddle(head);
}
return 0;
}
Java
// Java program to find middle of linked list
class LinkedList
{
Node head; // head of linked list
/* Linked list node */
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
/* Function to print middle of linked list */
void printMiddle()
{
Node slow_ptr = head;
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;
}
System.out.println("The middle element is [" +
slow_ptr.data + "] \n");
}
}
/* Inserts a new Node at front of the list. */
521
Chapter 87. Find the middle of a given linked list in C and Java
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
/* This function prints contents of linked list
starting from the given node */
public void printList()
{
Node tnode = head;
while (tnode != null)
{
System.out.print(tnode.data+"->");
tnode = tnode.next;
}
System.out.println("NULL");
}
public static void main(String [] args)
{
LinkedList llist = new LinkedList();
for (int i=5; i>0; --i)
{
llist.push(i);
llist.printList();
llist.printMiddle();
}
}
}
// This code is contributed by Rajat Mishra
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
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]
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>
/* Link list node */
struct node
{
int data;
struct node* next;
};
/* Function to get the middle of the linked list*/
void printMiddle(struct node *head)
{
int count = 0;
struct node *mid = head;
while (head != NULL)
{
/* update mid, when 'count' is odd number */
if (count & 1)
mid = mid->next;
++count;
head = head->next;
}
/* if empty list is provided */
if (mid != NULL)
printf("The middle element is [%d]\n\n", mid->data);
}
void push(struct node** head_ref, int new_data)
{
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));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
// A utility function to print a given linked list
void printList(struct node *ptr)
{
while (ptr != NULL)
{
printf("%d->", ptr->data);
ptr = ptr->next;
}
printf("NULL\n");
}
/* Drier program to test above function*/
int main()
{
/* Start with the empty list */
struct node* head = NULL;
int i;
for (i=5; i>0; i--)
{
push(&head, i);
printList(head);
printMiddle(head);
}
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
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
Method 1: (Recursive approach using system call stack)
Recursively traverse the linked list up to the end. Now during return from the function calls,
add up the last n nodes. The sum can be accumulated in some variable passed by reference
to the function or to some global variable.
// C++ implementation to find the sum of
// last 'n' nodes of the Linked List
#include <bits/stdc++.h>
using namespace std;
/* A Linked list node */
struct Node {
int data;
526
Chapter 88. Find the sum of last n nodes of the given Linked List
struct Node* next;
};
// function to insert a node at the
// beginning of the linked list
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node = new Node;
/* put in the data */
new_node->data = new_data;
/* link the old list to the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
// function to recursively find the sum of last
// 'n' nodes of the given linked list
void sumOfLastN_Nodes(struct Node* head, int* n,
int* sum)
{
// if head = NULL
if (!head)
return;
// recursively traverse the remaining nodes
sumOfLastN_Nodes(head->next, n, sum);
// if node count 'n' is greater than 0
if (*n > 0) {
// accumulate sum
*sum = *sum + head->data;
// reduce node count 'n' by 1
--*n;
}
}
// utility function to find the sum of last 'n' nodes
int sumOfLastN_NodesUtil(struct Node* head, int n)
{
// if n == 0
if (n <= 0)
527
Chapter 88. Find the sum of last n nodes of the given Linked List
return 0;
int sum = 0;
// find the sum of last 'n' nodes
sumOfLastN_Nodes(head, &n, &sum);
// required sum
return sum;
}
// Driver program to test above
int main()
{
struct Node* head = NULL;
// create linked list 10->6->8->4->12
push(&head, 12);
push(&head, 4);
push(&head, 8);
push(&head, 6);
push(&head, 10);
int n = 2;
cout << "Sum of last " << n << " nodes = "
<< sumOfLastN_NodesUtil(head, n);
return 0;
}
Output:
Sum of last 2 nodes = 16
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.
// C++ implementation to find the sum of last
// 'n' nodes of the Linked List
#include <bits/stdc++.h>
using namespace std;
/* A Linked list node */
528
Chapter 88. Find the sum of last n nodes of the given Linked List
struct Node {
int data;
struct Node* next;
};
// function to insert a node at the
// beginning of the linked list
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node = new Node;
/* put in the data */
new_node->data = new_data;
/* link the old list to the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
// utility function to find the sum of last 'n' nodes
int sumOfLastN_NodesUtil(struct Node* head, int n)
{
// if n == 0
if (n <= 0)
return 0;
stack<int> st;
int sum = 0;
// traverses the list from left to right
while (head != NULL) {
// push the node's data onto the stack 'st'
st.push(head->data);
// move to next node
head = head->next;
}
// pop 'n' nodes from 'st' and
// add them
while (n--) {
sum += st.top();
st.pop();
}
529
Chapter 88. Find the sum of last n nodes of the given Linked List
// required sum
return sum;
}
// Driver program to test above
int main()
{
struct Node* head = NULL;
// create linked list 10->6->8->4->12
push(&head, 12);
push(&head, 4);
push(&head, 8);
push(&head, 6);
push(&head, 10);
int n = 2;
cout << "Sum of last " << n << " nodes = "
<< sumOfLastN_NodesUtil(head, n);
return 0;
}
Output:
Sum of last 2 nodes = 16
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:
1. Reverse the given linked list.
2. Traverse the first n nodes of the reversed linked list.
3. While traversing add them.
4. Reverse the linked list back to its original order.
5. Return the added sum.
// C++ implementation to find the sum of last
// 'n' nodes of the Linked List
#include <bits/stdc++.h>
using namespace std;
/* A Linked list node */
struct Node {
530
Chapter 88. Find the sum of last n nodes of the given Linked List
int data;
struct Node* next;
};
// function to insert a node at the
// beginning of the linked list
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node = new Node;
/* put in the data */
new_node->data = new_data;
/* link the old list to the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
void reverseList(struct Node** head_ref)
{
struct Node* current, *prev, *next;
current = *head_ref;
prev = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}
// utility function to find the sum of last 'n' nodes
int sumOfLastN_NodesUtil(struct Node* head, int n)
{
// if n == 0
if (n <= 0)
return 0;
// reverse the linked list
reverseList(&head);
int sum = 0;
531
Chapter 88. Find the sum of last n nodes of the given Linked List
struct Node* current = head;
// traverse the 1st 'n' nodes of the reversed
// linked list and add them
while (current != NULL && & n--) {
// accumulate node's data to 'sum'
sum += current->data;
// move to next node
current = current->next;
}
// reverse back the linked list
reverseList(&head);
// required sum
return sum;
}
// Driver program to test above
int main()
{
struct Node* head = NULL;
// create linked list 10->6->8->4->12
push(&head, 12);
push(&head, 4);
push(&head, 8);
push(&head, 6);
push(&head, 10);
int n = 2;
cout << "Sum of last " << n << " nodes = "
<< sumOfLastN_NodesUtil(head, n);
return 0;
}
Output:
Sum of last 2 nodes = 16
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
1. Calculate the length of the given Linked List. Let it be len.
2. First traverse the (len – n) nodes from the beginning.
3. Then traverse the remaining n nodes and while traversing add them.
4. Return the added sum.
// C++ implementation to find the sum of last
// 'n' nodes of the Linked List
#include <bits/stdc++.h>
using namespace std;
/* A Linked list node */
struct Node {
int data;
struct Node* next;
};
// function to insert a node at the
// beginning of the linked list
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node = new Node;
/* put in the data */
new_node->data = new_data;
/* link the old list to the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
// utility function to find the sum of last 'n' nodes
int sumOfLastN_NodesUtil(struct Node* head, int n)
{
// if n == 0
if (n <= 0)
return 0;
int sum = 0, len = 0;
struct Node* temp = head;
// calculate the length of the linked list
while (temp != NULL) {
len++;
temp = temp->next;
}
533
Chapter 88. Find the sum of last n nodes of the given Linked List
// count of first (len - n) nodes
int c = len - n;
temp = head;
// just traverse the 1st 'c' nodes
while (temp != NULL && & c--)
// move to next node
temp = temp->next;
// now traverse the last 'n' nodes and add them
while (temp != NULL) {
// accumulate node's data to sum
sum += temp->data;
// move to next node
temp = temp->next;
}
// required sum
return sum;
}
// Driver program to test above
int main()
{
struct Node* head = NULL;
// create linked list 10->6->8->4->12
push(&head, 12);
push(&head, 4);
push(&head, 8);
push(&head, 6);
push(&head, 10);
int n = 2;
cout << "Sum of last " << n << " nodes = "
<< sumOfLastN_NodesUtil(head, n);
return 0;
}
Output:
Sum of last 2 nodes = 16
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.
// C++ implementation to find the sum of last
// 'n' nodes of the Linked List
#include <bits/stdc++.h>
using namespace std;
/* A Linked list node */
struct Node {
int data;
struct Node* next;
};
// function to insert a node at the
// beginning of the linked list
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node = new Node;
/* put in the data */
new_node->data = new_data;
/* link the old list to the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
// utility function to find the sum of last 'n' nodes
int sumOfLastN_NodesUtil(struct Node* head, int n)
{
// if n == 0
if (n <= 0)
return 0;
int sum = 0, temp = 0;
struct Node* ref_ptr, *main_ptr;
535
Chapter 88. Find the sum of last n nodes of the given Linked List
ref_ptr = main_ptr = head;
// traverse 1st 'n' nodes through 'ref_ptr' and
// accumulate all node's data to 'sum'
while (ref_ptr != NULL && & n--) {
sum += ref_ptr->data;
// move to next node
ref_ptr = ref_ptr->next;
}
// traverse to the end of the linked list
while (ref_ptr != NULL) {
// accumulate all node's data to 'temp' pointed
// by the 'main_ptr'
temp += main_ptr->data;
// accumulate all node's data to 'sum' pointed by
// the 'ref_ptr'
sum += ref_ptr->data;
// move both the pointers to their respective
// next nodes
main_ptr = main_ptr->next;
ref_ptr = ref_ptr->next;
}
// required sum
return (sum - temp);
}
// Driver program to test above
int main()
{
struct Node* head = NULL;
// create linked list 10->6->8->4->12
push(&head, 12);
push(&head, 4);
push(&head, 8);
push(&head, 6);
push(&head, 10);
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:
Sum of last 2 nodes = 16
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
Find unique elements in linked
list
Find unique elements in linked list - GeeksforGeeks
Given a linked list. We need to find unique elements in the linked list i.e, those elements
which are not repeated in the linked list or those elements whose frequency is 1. If No such
elements are present in list so Print ” No Unique Elements”.
Examples:
Input : 1 -> 4 -> 4 -> 2 -> 3 -> 5 -> 3 -> 4 -> 5
Output :1 2
Input :4 -> 5 -> 2 -> 5 -> 1 -> 4 -> 1 -> 2
Output :No Unique Elements
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
// C++ Program to Find the Unique elements in
// linked lists
#include <bits/stdc++.h>
using namespace std;
/* Linked list node */
struct Node {
int data;
struct Node* next;
};
/* 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;
}
// function to Find the unique elements in linked lists
void uniqueElements(struct Node* head)
{
// Initialize hash array that store the
// frequency of each element of list
unordered_map<int, int> hash;
for (Node *temp=head; temp!=NULL; temp=temp->next)
hash[temp->data]++;
int count = 0;
for (Node *temp=head; temp!=NULL; temp=temp->next) {
// Check whether the frequency of current
// element is 1 or not
if (hash[temp->data] == 1) {
cout << temp->data << " ";
count++;
}
}
// If No unique element in list
if (count == 0)
cout << " No Unique Elements ";
}
// Driver program to test above
539
Chapter 89. Find unique elements in linked list
int main()
{
struct Node* head = NULL;
// creating linked list
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 5);
push(&head, 3);
push(&head, 2);
push(&head, 4);
push(&head, 4);
push(&head, 1);
uniqueElements(head);
return 0;
}
Output:
1 2
Time Complexity : O(N)
Auxiliary Space : O(N)
Source
https://www.geeksforgeeks.org/find-unique-elements-linked-list/
540
Chapter 90
First common element in two
linked lists
First common element in two linked lists - GeeksforGeeks
Given two Linked Lists, find the first common element between given linked list i.e., we
need to find first node of first list which is also present in second list.
Examples:
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.
// C++ program to find first common element in
// two unsorted linked list
#include <bits/stdc++.h>
using namespace std;
/* Link list node */
struct Node {
int data;
struct Node* next;
541
Chapter 90. First common element in two linked lists
};
/* A utility function to insert a node at the
beginning of a linked list*/
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
/* Returns the first repeating element in linked list*/
int firstCommon(struct Node* head1, struct Node* head2)
{
// Traverse through every node of first list
for (; head1 != NULL; head1=head1->next)
// If current node is present in second list
for (Node *p = head2; p != NULL; p = p->next)
if (p->data == head1->data)
return head1->data;
// 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);
struct Node* head2 = NULL;
push(&head2, 10);
push(&head2, 2);
push(&head2, 15);
push(&head2, 8);
cout << firstCommon(head1, head2);
return 0;
}
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
First non-repeating in a linked
list
First non-repeating in a linked list - GeeksforGeeks
Given a linked list, find its first non-repeating integer element.
Examples:
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.
1) Create a hash table and marked all element as zero.
2) Traverse the linked list and count the frequency of all the element in hashtable.
3) Traverse the linked list again and see the element who’s frequency is 1 in hashtable.
// C++ program to find first non-repeating
// element in a linked list
#include<bits/stdc++.h>
using namespace std;
/* Link list node */
struct Node
{
int data;
struct Node* next;
544
Chapter 91. First non-repeating in a linked list
};
/* Function to find the first non-repeating
element in the linked list */
int firstNonRepeating(struct Node *head)
{
// Create an empty map and insert all linked
// list elements into hash table
unordered_map<int, int> mp;
for (Node *temp=head; temp!=NULL; temp=temp->next)
mp[temp->data]++;
// Traverse the linked list again and return
// the first node whose count is 1
for (Node *temp=head; temp!=NULL; temp=temp->next)
if (mp[temp->data] == 1)
return temp->data;
return -1;
}
/* Function to push a node */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
/* Driver program to test above function*/
int main()
{
// Let us create below linked list.
// 85->15->18->20->85->35->4->20->NULL
struct Node* head = NULL;
push(&head, 20);
push(&head, 4);
push(&head, 35);
push(&head, 85);
push(&head, 20);
push(&head, 18);
push(&head, 15);
push(&head, 85);
cout << firstNonRepeating(head);
return 0;
}
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
Flatten a binary tree into linked
list
Flatten a binary tree into linked list - GeeksforGeeks
Given a binary tree, flatten it into linked list in-place. Usage of auxiliary data structure
is not allowed. After flattening, left of each node should point to NULL and right should
contain next node in level order.
Examples:
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,
/* Program to flatten a given Binary
Tree into linked list */
#include <iostream>
using namespace std;
548
Chapter 92. Flatten a binary tree into linked list
struct Node {
int key;
Node *left, *right;
};
/* utility that allocates a new Node
with the given key */
Node* newNode(int key)
{
Node* node = new Node;
node->key = key;
node->left = node->right = NULL;
return (node);
}
// Function to convert binary tree into
// linked list by altering the right node
// and making left node point to NULL
void flatten(struct Node* root)
{
// base condition- return if root is NULL
// or if it is a leaf node
if (root == NULL || root->left == NULL &&
root->right == NULL) {
return;
}
// if root->left exists then we have
// to make it root->right
if (root->left != NULL) {
// move left recursively
flatten(root->left);
// store the node root->right
struct Node* tmpRight = root->right;
root->right = root->left;
root->left = NULL;
// find the position to insert
// the stored value
struct Node* t = root->right;
while (t->right != NULL) {
t = t->right;
}
// insert the stored value
t->right = tmpRight;
549
Chapter 92. Flatten a binary tree into linked list
// now call the same function
// for root->right
flatten(root->right);
}
// To find the inorder traversal
void inorder(struct Node* root)
{
// base condition
if (root == NULL)
return;
inorder(root->left);
cout << root->key << " ";
inorder(root->right);
}
/* Driver program to test above functions*/
int main()
{
/* 1
/ \
2 5
/ \ \
3 4 6 */
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(5);
root->left->left = newNode(3);
root->left->right = newNode(4);
root->right->right = newNode(6);
flatten(root);
cout << "The Inorder traversal after "
"flattening binary tree ";
inorder(root);
return 0;
}
Output:
The Inorder traversal after flattening
binary tree 1 2 3 4 5 6
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
Flatten a binary tree into linked
list | Set-2
Flatten a binary tree into linked list | Set-2 - GeeksforGeeks
Given a binary tree, flatten it into a linked list. After flattening, the left of each node should
point to NULL and right should contain next node in level order.
Example:
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:
// C++ program to flatten the linked
// list using stack | set-2
#include <iostream>
#include <stack>
using namespace std;
struct Node {
int key;
Node *left, *right;
};
/* utility that allocates a new Node
with the given key */
Node* newNode(int key)
{
Node* node = new Node;
node->key = key;
node->left = node->right = NULL;
return (node);
}
// To find the inorder traversal
553
Chapter 93. Flatten a binary tree into linked list | Set-2
void inorder(struct Node* root)
{
// base condition
if (root == NULL)
return;
inorder(root->left);
cout << root->key << " ";
inorder(root->right);
}
// Function to convert binary tree into
// linked list by altering the right node
// and making left node point to NULL
Node* solution(Node* A)
{
// Declare a stack
stack<Node*> st;
Node* ans = A;
// Iterate till the stack is not empty
// and till root is Null
while (A != NULL || st.size() != 0) {
// Check for NULL
if (A->right != NULL) {
st.push(A->right);
}
// Make the Right Left and
// left NULL
A->right = A->left;
A->left = NULL;
// Check for NULL
if (A->right == NULL && st.size() != 0) {
A->right = st.top();
st.pop();
}
// 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 */
// Build the tree
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(5);
root->left->left = newNode(3);
root->left->right = newNode(4);
root->right->right = newNode(6);
// Call the function to
// flatten the tree
root = solution(root);
cout << "The Inorder traversal after "
"flattening binary tree ";
// call the function to print
// inorder after flatenning
inorder(root);
return 0;
return 0;
}
Output:
The Inorder traversal after flattening binary tree 1 2 3 4 5 6
Time Complexity: O(N)
Auxiliary Space: O(Log N)
Source
https://www.geeksforgeeks.org/flatten-a-binary-tree-into-linked-list-set-2/
555
Chapter 94
Flatten a multi-level linked list |
Set 2 (Depth wise)
Flatten a multi-level linked list | Set 2 (Depth wise) - GeeksforGeeks
We have discussed flattening of a multi-level linked list where nodes have two pointers down
and next. In the previous post, we flattened the linked list level wise. How to flatten a
linked list when we always need to process down pointer before next at every node.
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)
Source : Oracle Interview
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.
// C++ program to flatten a multilevel linked list
#include <bits/stdc++.h>
using namespace std;
// A Linked List Node
struct Node
{
int data;
struct Node *next;
struct Node *down;
};
// Flattens a multi-level linked list depth wise
Node* flattenList(Node* node)
{
// Base case
if (node == NULL)
return NULL;
// To keep track of last visited node
// (NOTE: This is static)
static Node *last;
last = node;
// Store next pointer
Node *next = node->next;
// If down list exists, process it first
// Add down list as next of current node
if (node->down)
node->next = flattenList(node->down);
// If next exists, add it after the next
// of last added node
if (next)
last->next = flattenList(next);
557
Chapter 94. Flatten a multi-level linked list | Set 2 (Depth wise)
return node;
}
// Utility method to print a linked list
void printFlattenNodes(Node* head)
{
while (head)
{
printf("%d ", head->data);
head = head->next;
}
}
// Utility function to create a new node
Node* newNode(int new_data)
{
Node* new_node = new Node;
new_node->data = new_data;
new_node->next = new_node->down = NULL;
return new_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);
// Flatten list and print modified list
head = flattenList(head);
printFlattenNodes(head);
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
Flatten a multilevel linked list
Flatten a multilevel linked list - GeeksforGeeks
Given a linked list where in addition to the next pointer, each node has a child pointer,
which may or may not point to a separate list. These child lists may have one or more
children of their own, and so on, to produce a multilevel data structure, as shown in below
figure.You are given the head of the first level of the list. Flatten the list so that all the
nodes appear in a single-level linked list. You need to flatten the list in way that all nodes
at first level should come first, then nodes of second level, and so on.
Each node is a C struct with the following definition.
struct List
{
int data;
struct List *next;
struct List *child;
};
The above list should be converted to 10->5->12->7->11->4->20->13->17-
>6->2->16->9->8->3->19->15
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
Following is the implementation of the above algorithm.
// Program to flatten list with next and child pointers
#include <stdio.h>
#include <stdlib.h>
// Macro to find number of elements in array
#define SIZE(arr) (sizeof(arr)/sizeof(arr[0]))
// A linked list node has data, next pointer and child pointer
struct Node
{
int data;
struct Node *next;
struct Node *child;
};
// A utility function to create a linked list with n nodes. The data
// of nodes is taken from arr[]. All child pointers are set as NULL
struct Node *createList(int *arr, int n)
{
struct Node *head = NULL;
struct Node *p;
int i;
561
Chapter 95. Flatten a multilevel linked list
for (i = 0; i < n; ++i) {
if (head == NULL)
head = p = (struct Node *)malloc(sizeof(*p));
else {
p->next = (struct Node *)malloc(sizeof(*p));
p = p->next;
}
p->data = arr[i];
p->next = p->child = NULL;
}
return head;
}
// A utility function to print all nodes of a linked list
void printList(struct Node *head)
{
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
// 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};
/* create 8 linked lists */
struct Node *head1 = createList(arr1, SIZE(arr1));
struct Node *head2 = createList(arr2, SIZE(arr2));
struct Node *head3 = createList(arr3, SIZE(arr3));
struct Node *head4 = createList(arr4, SIZE(arr4));
struct Node *head5 = createList(arr5, SIZE(arr5));
struct Node *head6 = createList(arr6, SIZE(arr6));
struct Node *head7 = createList(arr7, SIZE(arr7));
struct Node *head8 = createList(arr8, SIZE(arr8));
/* modify child pointers to create the list shown above */
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;
}
/* The main function that flattens a multilevel linked list */
void flattenList(struct Node *head)
{
/*Base case*/
if (head == NULL)
return;
struct Node *tmp;
/* Find tail node of first level linked list */
struct Node *tail = head;
while (tail->next != NULL)
tail = tail->next;
// One by one traverse through all nodes of first level
// linked list till we reach the tail node
struct Node *cur = head;
while (cur != tail)
{
// If current node has a child
if (cur->child)
{
// then append the child at the end of current list
tail->next = cur->child;
// and update the tail to new last node
tmp = cur->child;
while (tmp->next)
tmp = tmp->next;
tail = tmp;
}
// Change current node
cur = cur->next;
563
Chapter 95. Flatten a multilevel linked list
}
}
// A driver program to test above functions
int main(void)
{
struct Node *head = NULL;
head = createList();
flattenList(head);
printList(head);
return 0;
}
Java
// Java program to flatten linked list with next and child pointers
class LinkedList {
static Node head;
class Node {
int data;
Node next, child;
Node(int d) {
data = d;
next = child = null;
}
}
// A utility function to create a linked list with n nodes. The data
// of nodes is taken from arr[]. All child pointers are set as NULL
Node createList(int arr[], int n) {
Node node = null;
Node p = 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;
}
// A utility function to print all nodes of a linked list
void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
System.out.println("");
}
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};
/* create 8 linked lists */
Node head1 = createList(arr1, arr1.length);
Node head2 = createList(arr2, arr2.length);
Node head3 = createList(arr3, arr3.length);
Node head4 = createList(arr4, arr4.length);
Node head5 = createList(arr5, arr5.length);
Node head6 = createList(arr6, arr6.length);
Node head7 = createList(arr7, arr7.length);
Node head8 = createList(arr8, arr8.length);
/* modify child pointers to create the list shown above */
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;
}
/* The main function that flattens a multilevel linked list */
void flattenList(Node node) {
565
Chapter 95. Flatten a multilevel linked list
/*Base case*/
if (node == null) {
return;
}
Node tmp = null;
/* Find tail node of first level linked list */
Node tail = node;
while (tail.next != null) {
tail = tail.next;
}
// One by one traverse through all nodes of first level
// linked list till we reach the tail node
Node cur = node;
while (cur != tail) {
// If current node has a child
if (cur.child != null) {
// then append the child at the end of current list
tail.next = cur.child;
// and update the tail to new last node
tmp = cur.child;
while (tmp.next != null) {
tmp = tmp.next;
}
tail = tmp;
}
// Change current node
cur = cur.next;
}
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
head = list.createList();
list.flattenList(head);
list.printList(head);
}
}
// This code has been contributed by Mayank Jaiswal
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
Flattening a Linked List
Flattening a Linked List - GeeksforGeeks
Given a linked list where every node represents a linked list and contains two pointers of its
type:
(i) Pointer to next node in the main list (we call it ‘right’ pointer in below code)
(ii) Pointer to a linked list where this node is head (we call it ‘down’ pointer in below code).
All linked lists are sorted. See the following example
5 -> 10 -> 19 -> 28
| | | |
V V V V
7 20 22 35
| | |
V V V
8 50 40
| |
V V
30 45
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
// C program for flattening a linked list
#include <stdio.h>
#include <stdlib.h>
// A Linked List Node
typedef struct Node
{
int data;
struct Node *right;
struct Node *down;
} Node;
/* A utility function to insert a new node at the begining
of linked list */
void push (Node** head_ref, int new_data)
{
/* allocate node */
Node* new_node = (Node *) malloc(sizeof(Node));
new_node->right = NULL;
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->down = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print nodes in the flattened linked list */
void printList(Node *node)
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->down;
}
}
// A utility function to merge two sorted linked lists
Node* merge( Node* a, Node* b )
{
// If first list is empty, the second list is result
if (a == NULL)
return b;
// If second list is empty, the second list is result
569
Chapter 96. Flattening a Linked List
if (b == NULL)
return a;
// Compare the data members of head nodes of both lists
// and put the smaller one in result
Node* result;
if (a->data < b->data)
{
result = a;
result->down = merge( a->down, b );
}
else
{
result = b;
result->down = merge( a, b->down );
}
return result;
}
// The main function that flattens a given linked list
Node* flatten (Node* root)
{
// Base cases
if (root == NULL || root->right == NULL)
return root;
// Merge this list with the list on right side
return merge( root, flatten(root->right) );
}
// Driver program to test above functions
int main()
{
Node* root = NULL;
/* Let us create the following linked list
5 -> 10 -> 19 -> 28
| | | |
V V V V
7 20 22 35
| | |
V V V
8 50 40
| |
V V
30 45
*/
570
Chapter 96. Flattening a Linked List
push( &root, 30 );
push( &root, 8 );
push( &root, 7 );
push( &root, 5 );
push( &( root->right ), 20 );
push( &( root->right ), 10 );
push( &( root->right->right ), 50 );
push( &( root->right->right ), 22 );
push( &( root->right->right ), 19 );
push( &( root->right->right->right ), 45 );
push( &( root->right->right->right ), 40 );
push( &( root->right->right->right ), 35 );
push( &( root->right->right->right ), 20 );
// Let us flatten the list
root = flatten(root);
// Let us print the flatened linked list
printList(root);
return 0;
}
Java
// Java program for flattening a Linked List
class LinkedList
{
Node head; // head of list
/* Linked list Node*/
class Node
{
int data;
Node right, down;
Node(int data)
{
this.data = data;
right = null;
down = null;
}
}
// An utility function to merge two sorted linked lists
Node merge(Node a, Node b)
571
Chapter 96. Flattening a Linked List
{
// if first linked list is empty then second
// is the answer
if (a == null) return b;
// if second linked list is empty then first
// is the result
if (b == null) return a;
// compare the data members of the two linked lists
// and put the larger one in the result
Node result;
if (a.data < b.data)
{
result = a;
result.down = merge(a.down, b);
}
else
{
result = b;
result.down = merge(a, b.down);
}
return result;
}
Node flatten(Node root)
{
// Base Cases
if (root == null || root.right == null)
return root;
// recur for list on right
root.right = flatten(root.right);
// now merge
root = merge(root, root.right);
// return the root
// it will be in turn merged with its left
return root;
}
/* Utility function to insert a node at begining of the
linked list */
Node push(Node head_ref, int data)
572
Chapter 96. Flattening a Linked List
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(data);
/* 3. Make next of new Node as head */
new_node.down = head_ref;
/* 4. Move the head to point to new Node */
head_ref = new_node;
/*5. return to link it back */
return head_ref;
}
void printList()
{
Node temp = head;
while (temp != null)
{
System.out.print(temp.data + " ");
temp = temp.down;
}
System.out.println();
}
/* Drier program to test above functions */
public static void main(String args[])
{
LinkedList L = new LinkedList();
/* Let us create the following linked list
5 -> 10 -> 19 -> 28
| | | |
V V V V
7 20 22 35
| | |
V V V
8 50 40
| |
V V
30 45
*/
L.head = L.push(L.head, 30);
L.head = L.push(L.head, 8);
L.head = L.push(L.head, 7);
L.head = L.push(L.head, 5);
573
Chapter 96. Flattening a Linked List
L.head.right = L.push(L.head.right, 20);
L.head.right = L.push(L.head.right, 10);
L.head.right.right = L.push(L.head.right.right, 50);
L.head.right.right = L.push(L.head.right.right, 22);
L.head.right.right = L.push(L.head.right.right, 19);
L.head.right.right.right = L.push(L.head.right.right.right, 45);
L.head.right.right.right = L.push(L.head.right.right.right, 40);
L.head.right.right.right = L.push(L.head.right.right.right, 35);
L.head.right.right.right = L.push(L.head.right.right.right, 20);
// flatten the list
L.head = L.flatten(L.head);
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
Function to check if a singly
linked list is palindrome
Function to check if a singly linked list is palindrome - GeeksforGeeks
Given a singly linked list of characters, write a function that returns true if the given list is
palindrome, else false.
METHOD 1 (Use a Stack)
A simple solution is to use a stack of list nodes. This mainly involves three steps.
1) Traverse the given list from head to tail and push every visited node to stack.
2) Traverse the list again. For every visited node, pop a node from stack and compare data
of popped node with currently visited node.
3) If all nodes matched, then return true, else false.
Time complexity of above method is O(n), but it requires O(n) extra space. Following
methods solve this with constant extra space.
METHOD 2 (By reversing the list)
This method takes O(n) time and O(1) extra space.
1) Get the middle of the linked list.
2) Reverse the second half of the linked list.
3) Check if the first half and second half are identical.
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
/* Program to check if a linked list is palindrome */
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
/* Link list node */
struct Node
{
char data;
struct Node* next;
};
void reverse(struct Node**);
bool compareLists(struct Node*, struct Node *);
/* Function to check if given linked list is
palindrome or not */
bool isPalindrome(struct Node *head)
{
struct Node *slow_ptr = head, *fast_ptr = head;
struct Node *second_half, *prev_of_slow_ptr = head;
struct Node *midnode = NULL; // To handle odd size list
bool res = true; // initialize result
if (head!=NULL && head->next!=NULL)
{
/* Get the middle of the list. Move slow_ptr by 1
and fast_ptrr by 2, slow_ptr will have the middle
node */
while (fast_ptr != NULL && fast_ptr->next != NULL)
{
fast_ptr = fast_ptr->next->next;
/*We need previous of the slow_ptr for
linked lists with odd elements */
prev_of_slow_ptr = slow_ptr;
slow_ptr = slow_ptr->next;
}
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
/* Construct the original list back */
reverse(&second_half); // Reverse the second half again
// If there was a mid node (odd size case) which
// was not part of either first half or second half.
if (midnode != NULL)
{
prev_of_slow_ptr->next = midnode;
midnode->next = second_half;
}
else prev_of_slow_ptr->next = second_half;
}
return res;
}
/* Function to reverse the linked list Note that this
function may change the head */
void reverse(struct Node** head_ref)
{
struct Node* prev = NULL;
struct Node* current = *head_ref;
struct Node* next;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
577
Chapter 97. Function to check if a singly linked list is palindrome
/* Function to check if two input lists have same data*/
bool compareLists(struct Node* head1, struct Node *head2)
{
struct Node* temp1 = head1;
struct Node* temp2 = head2;
while (temp1 && temp2)
{
if (temp1->data == temp2->data)
{
temp1 = temp1->next;
temp2 = temp2->next;
}
else return 0;
}
/* Both are empty reurn 1*/
if (temp1 == NULL && temp2 == NULL)
return 1;
/* Will reach here when one is NULL
and other is not */
return 0;
}
/* 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));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to pochar to the new node */
(*head_ref) = new_node;
}
// A utility function to print a given linked list
void printList(struct node *ptr)
{
578
Chapter 97. Function to check if a singly linked list is palindrome
while (ptr != NULL)
{
printf("%c->", ptr->data);
ptr = ptr->next;
}
printf("NULL\n");
}
/* Drier program to test above function*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
char str[] = "abacaba";
int i;
for (i = 0; str[i] != '\0'; i++)
{
push(&head, str[i]);
printList(head);
isPalindrome(head)? printf("Is Palindrome\n\n"):
printf("Not Palindrome\n\n");
}
return 0;
}
Java
/* Java program to check if linked list is palindrome */
class LinkedList
{
Node head; // head of list
Node slow_ptr, fast_ptr,second_half;
/* Linked list Node*/
class Node
{
char data;
Node next;
Node(char d)
{
data = d;
next = null;
}
579
Chapter 97. Function to check if a singly linked list is palindrome
/* Function to check if given linked list is
palindrome or not */
boolean isPalindrome(Node head)
{
slow_ptr = head; fast_ptr = head;
Node prev_of_slow_ptr = head;
Node midnode = null; // To handle odd size list
boolean res = true; // initialize result
if (head != null && head.next != null)
{
/* Get the middle of the list. Move slow_ptr by 1
and fast_ptrr by 2, slow_ptr will have the middle
node */
while (fast_ptr != null && fast_ptr.next != null)
{
fast_ptr = fast_ptr.next.next;
/*We need previous of the slow_ptr for
linked lists with odd elements */
prev_of_slow_ptr = slow_ptr;
slow_ptr = slow_ptr.next;
}
/* fast_ptr would become NULL when there are even elements
in the 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(); // Reverse the second half
res = compareLists(head, second_half); // compare
/* Construct the original list back */
reverse(); // Reverse the second half again
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
// was not part of either first half or second half.
prev_of_slow_ptr.next = midnode;
midnode.next = second_half;
} else
prev_of_slow_ptr.next = second_half;
}
return res;
}
/* Function to reverse the linked list Note that this
function may change the head */
void reverse()
{
Node prev = null;
Node current = second_half;
Node next;
while (current != null)
{
next = current.next;
current.next = prev;
prev = current;
current = next;
}
second_half = prev;
}
/* Function to check if two input lists have same data*/
boolean compareLists(Node head1, Node head2)
{
Node temp1 = head1;
Node temp2 = head2;
while (temp1 != null && temp2 != null)
{
if (temp1.data == temp2.data)
{
temp1 = temp1.next;
temp2 = temp2.next;
} else
return false;
}
/* Both are empty reurn 1*/
if (temp1 == null && temp2 == null)
return true;
/* Will reach here when one is NULL
and other is not */
581
Chapter 97. Function to check if a singly linked list is palindrome
return false;
}
/* Push a node to linked list. Note that this function
changes the head */
public void push(char new_data)
{
/* Allocate the Node &
Put in the data */
Node new_node = new Node(new_data);
/* link the old list off the new one */
new_node.next = head;
/* Move the head to point to new Node */
head = new_node;
}
// A utility function to print a given linked list
void printList(Node ptr)
{
while (ptr != null)
{
System.out.print(ptr.data + "->");
ptr = ptr.next;
}
System.out.println("NULL");
}
/* Driver program to test the above functions */
public static void main(String[] args) {
/* Start with the empty list */
LinkedList llist = new LinkedList();
char str[] = {'a', 'b', 'a', 'c', 'a', 'b', 'a'};
String string = new String(str);
for (int i = 0; i< 7 ; i++) {
llist.push(str[i]);
llist.printList(llist.head);
if (llist.isPalindrome(llist.head) != false)
{
System.out.println("Is Palindrome");
System.out.println("");
}
else
{
System.out.println("Not Palindrome");
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
Time Complexity O(n)
Auxiliary Space: O(1)
METHOD 3 (Using Recursion)
Use two pointers left and right. Move right and left using recursion and check for following
in each recursive call.
1) Sub-list is palindrome.
2) Value at current left and right are matching.
If both above conditions are true then return true.
The idea is to use function call stack as container. Recursively traverse till the end of list.
When we return from last NULL, we will be at last node. The last node to be compared
with first node of list.
In order to access first node of list, we need list head to be available in the last call of
recursion. Hence we pass head also to the recursive function. If they both match we need to
compare (2, n-2) nodes. Again when recursion falls back to (n-2)nd node, we need reference
to 2nd node from head. We advance the head pointer in previous call, to refer to next node
in the list.
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
// Recursive program to check if a given linked list is palindrome
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
/* Link list node */
struct node
{
char data;
struct node* next;
};
// Initial parameters to this function are &head and head
bool isPalindromeUtil(struct node **left, struct node *right)
{
/* stop recursion when right becomes NULL */
if (right == NULL)
return true;
/* If sub-list is not palindrome then no need to
check for current left and right, return false */
bool isp = isPalindromeUtil(left, right->next);
if (isp == false)
return false;
/* Check values at current left and right */
bool isp1 = (right->data == (*left)->data);
/* Move left to next node */
*left = (*left)->next;
return isp1;
}
// A wrapper over isPalindromeUtil()
bool isPalindrome(struct node *head)
{
isPalindromeUtil(&head, head);
}
/* Push a node to linked list. Note that this function
584
Chapter 97. Function to check if a singly linked list is palindrome
changes the head */
void push(struct node** head_ref, char new_data)
{
/* allocate node */
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to pochar to the new node */
(*head_ref) = new_node;
}
// A utility function to print a given linked list
void printList(struct node *ptr)
{
while (ptr != NULL)
{
printf("%c->", ptr->data);
ptr = ptr->next;
}
printf("NULL\n");
}
/* Drier program to test above function*/
int main()
{
/* Start with the empty list */
struct node* head = NULL;
char str[] = "abacaba";
int i;
for (i = 0; str[i] != '\0'; i++)
{
push(&head, str[i]);
printList(head);
isPalindrome(head)? printf("Is Palindrome\n\n"):
printf("Not Palindrome\n\n");
}
return 0;
}
Java
585
Chapter 97. Function to check if a singly linked list is palindrome
/* Java program to check if linked list is palindrome recursively */
class LinkedList
{
Node head; // head of list
Node left;
/* Linked list Node*/
class Node
{
char data;
Node next;
Node(char d)
{
data = d;
next = null;
}
}
// Initial parameters to this function are &head and head
boolean isPalindromeUtil(Node right)
{
left = head;
/* stop recursion when right becomes NULL */
if (right == null)
return true;
/* If sub-list is not palindrome then no need to
check for current left and right, return false */
boolean isp = isPalindromeUtil(right.next);
if (isp == false)
return false;
/* Check values at current left and right */
boolean isp1 = (right.data == (left).data);
/* Move left to next node */
left = left.next;
return isp1;
}
// A wrapper over isPalindromeUtil()
boolean isPalindrome(Node head)
{
boolean result = isPalindromeUtil(head);
586
Chapter 97. Function to check if a singly linked list is palindrome
return result;
}
/* Push a node to linked list. Note that this function
changes the head */
public void push(char new_data)
{
/* Allocate the Node &
Put in the data */
Node new_node = new Node(new_data);
/* link the old list off the new one */
new_node.next = head;
/* Move the head to point to new Node */
head = new_node;
}
// A utility function to print a given linked list
void printList(Node ptr)
{
while (ptr != null)
{
System.out.print(ptr.data + "->");
ptr = ptr.next;
}
System.out.println("NULL");
}
/* Driver program to test the above functions */
public static void main(String[] args)
{
/* Start with the empty list */
LinkedList llist = new LinkedList();
char str[] = {'a', 'b', 'a', 'c', 'a', 'b', 'a'};
String string = new String(str);
for (int i = 0; i < 7; i++)
{
llist.push(str[i]);
llist.printList(llist.head);
if (llist.isPalindrome(llist.head) != false)
{
System.out.println("Is Palindrome");
System.out.println("");
}
else
{
587
Chapter 97. Function to check if a singly linked list is palindrome
System.out.println("Not Palindrome");