-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLinkedList.txt
1258 lines (1080 loc) · 35.9 KB
/
LinkedList.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
SOLUTIONS OF THESE QUESTIONS ARE EITHER ON GFG OR ON LEETCODE.
---------------------------------------LINKED LIST-----------------------------------------
1. Reverse Linked List (both Iteratively and Recursively)
-> Iteratively
public void RPI() {
Node prev = head;
Node curr = head.next;
Node ahead;
while (curr != null) {
ahead = curr.next;
curr.next = prev;
prev = curr;
curr = ahead;
}
// head tail swap
Node temp = head;
head = tail;
tail = temp;
tail.next = null;
}
-> if tail is not there
Best-1)
public ListNode reverseList(ListNode head) {
if(head==null){
return null;
}else if(head.next==null){
return head;
}
ListNode prev= head;
ListNode curr=head.next;
ListNode ahead;
while(curr!=null){
ahead=curr.next;
curr.next=prev;
prev=curr;
curr=ahead;
}
ListNode temp=head;
head=prev;
prev=temp;
prev.next=null;
return head;
}
Best-2)
static Node reverse(Node head) {
if (head == null || head.next == null) return head;
Node tail = reverse(head.next);
head.next.next = head;
head.next = null;
return tail;
}
-> Recursively
public void RPR() {
RPR(head, head.next);
Node temp = head;
head = tail;
tail = temp;
tail.next = null;
}
private void RPR(Node prev, Node curr) {
if (curr == null) {
return;
}
// another method
// Node ahead = curr.next;
// curr.next = prev;
// RPR(curr, ahead);
RPR(curr, curr.next);
curr.next = prev;
}
-> Another Method
public ListNode reverseList(ListNode head) {
if(head==null)
return head;
ListNode p=solve(head);
p.next=null;
return glob;
}
static ListNode glob=null;
public ListNode solve(ListNode node){
if(node.next==null){
glob=node;
return node;
}
ListNode temp = solve(node.next);
temp.next=node;
return node;
}
--------------------------------------------------------------------------------------------------------
2. Detect Loop in LinkedList.->https://www.youtube.com/watch?v=LUm2ABqAs1w
#Floyd cycle detection algorithm
public static boolean detectLoop(Node head){
Node slow=head;
Node fast=head;
while(fast!=null && fast.next!=null){
slow=slow.next;
fast=fast.next.next;
if(slow==fast)
return true;
}
return false;
}
--------------------------------------------------------------------------------------------------------
3. Find first node of loop in a linked list
public ListNode detectCycle(ListNode head) {
//works for one node
if(head==null||head.next==null){
return null;
}
ListNode slow=head;
ListNode fast=head;
while(fast!=null && fast.next!=null){
slow=slow.next;
fast=fast.next.next;
if(slow==fast)
break;
}
if(slow!=fast){
return null;
}
slow=head;
while(slow!=fast){
slow=slow.next;
fast=fast.next;
}
return slow;
}
--------------------------------------------------------------------------------------------------------
4. Remove loop from LinkedList
public static void removeLoop(Node head){
if (head == null || head.next == null)
return;
Node slow=head;
Node fast=head;
while(fast!=null && fast.next!=null){
slow=slow.next;
fast=fast.next.next;
if(slow==fast)
break;
}
//when first element is the starting of the loop
if(slow==head){
while(fast.next!=slow){
fast=fast.next;
}
fast.next=null;
}else if(slow==fast){
slow=head;
while(slow.next!=fast.next){
slow=slow.next;
fast=fast.next;
}
fast.next=null;
}
}
--------------------------------------------------------------------------------------------------------
5. Middle element of Linked list
public int mid() {
Node slow = head;
Node fast = head;
while (fast.next != null && (fast.next).next != null) { // in even case it gives 1st mid
// while(fast!=null&&fast.next!=null) { // in even case it gives 2nd mid
slow = slow.next;
fast = (fast.next).next;
}
return slow.data;
}
--------------------------------------------------------------------------------------------------------
6. Reverse Nodes in k-Group O(N),S(1)->https://www.youtube.com/watch?v=Of0HPkk3JgI
public ListNode reverseKGroup(ListNode head, int k) {
if(head==null||k==1){
return head;
}
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode curr=dummy,pre=dummy,next=dummy;
int count=0;
while(curr.next!=null){
count++;
curr=curr.next;
}
To not reverse last nodes if rem node are less than k
-------------------------------->
while(count>=k){
curr=pre.next;
next=curr.next;
for(int i=1;i<=k-1;i++){ //as we want to change k-1 links
curr.next=next.next;
next.next=pre.next;
pre.next=next;
next=curr.next;
}
pre=curr;
count-=k;
}
To Reverse the last nodes even if rem nodes are less than k
-------------------------------->
while(count>=k){
if(count>=0){ // change it to k to covert it for upper task
curr=pre.next;
next=curr.next;
for(int i=1;i<=k-1 && curr.next!=null;i++){ //as we want to change k-1 links
curr.next=next.next;
next.next=pre.next;
pre.next=next;
next=curr.next;
}
pre=curr;
count-=k;
continue;
}
k = count;
curr=pre.next;
next=curr.next;
for(int i=1;i<=k-1 && curr.next!=null;i++){ //as we want to change k-1 links
curr.next=next.next;
next.next=pre.next;
pre.next=next;
next=curr.next;
}
pre=curr;
break;
}
-------------------------------->
return dummy.next;
}
### Reverse K alternate nodes
-> https://www.techiedelight.com/reverse-alternate-group-k-nodes-linked-list/
public static Node reverse(NodeWrapper curr, int k)
{
// maintain a `prev` pointer
Node prev = null;
// traverse the list and reverse first `k` nodes
while (curr.node != null && k-- > 0)
{
// tricky: note the next node
Node next = curr.node.next;
// fix the `curr` node
curr.node.next = prev;
// advance the two pointers
prev = curr.node;
curr.node = next;
}
// return node at the front
return prev;
}
// Function to skip `k` nodes in a given linked list. Note that the
// linked list is passed by reference using `NodeWrapper` class.
public static Node skipKNodes(NodeWrapper curr, int k)
{
Node prev = null;
while (curr.node != null && k-- > 0)
{
prev = curr.node;
curr.node = curr.node.next;
}
return prev;
}
// Recursive function to reverse every alternate group of `k` nodes
// in a linked list
public static Node reverseAlternatingKNodes(Node head, int k)
{
Node prev = null;
// Wrap current node, so its reference can be changed inside the
// `reverse()` and `skipKNodes()` method
NodeWrapper curr = new NodeWrapper(head);
// traverse the whole list
while (curr.node != null)
{
// curr would be the last node in the reversed sublist
Node lastNode = curr.node;
// reverse next `k` nodes and get their head
Node frontNode = reverse(curr, k);
// update head pointer after first `reverse()` call
if (prev == null) {
head = frontNode;
}
// for subsequent calls to `reverse()`, link the reversed sublist
// with the rest of the list
else {
prev.next = frontNode;
}
// link the last node with the current node
lastNode.next = curr.node;
// skip next `k` nodes
prev = skipKNodes(curr, k);
}
// return head node
return head;
}
--------------------------------------------------------------------------------------------------------
7. Delete nodes having greater value on right
Node DeleteNodeRightLarger(Node head){
//Reverse the linkedlist for easy intuition
head=reverseLL(head);
Node curr=head.next;
Node max=head;
while(curr!=null){
if(max.data<=curr.data){
max=curr;
curr=curr.next;
}else{
curr=curr.next;
max.next=curr;
}
}
max.next=null;
head=reverseLL(head);
return head;
}
--------------------------------------------------------------------------------------------------------
8. Add two linked list in S(1)
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head=l1; //we will store the ans in l1
ListNode prev=null; //this will help to join the link if l1 is smaller than l2
int carry=0;
while(l1!=null && l2!=null){
int sum=l1.val+l2.val+carry;
carry=sum/10;
l1.val=sum%10;
prev=l1; //acts like a pointer
l1=l1.next;
l2=l2.next;
}
if(l2!=null){
prev.next=l2; //linking as l2 is bigger than l1
l1=l2; //now assigning l1 as l2 because we don't want to make a new node-(using space)
}
while(l1!=null){
int sum=l1.val+carry;
carry=sum/10;
l1.val=sum%10;
prev=l1;
l1=l1.next;
}
if(carry!=0){
prev.next=new ListNode(carry);
}
return head;
}
# Add one to linked list
-> firstly reverse the linked list
->add 1 using the same method as above
-> Again reverse the linked list
--------------------------------------------------------------------------------------------------------
9. Remove duplicates from sorted List O(N) S(1)
public ListNode deleteDuplicates(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode prev=head;
ListNode curr=prev.next;
while(curr!=null){
if(prev.val==curr.val){
curr=curr.next;
prev.next=curr;
}else{
prev=curr;
curr=curr.next;
}
}
return head;
}
#) Delete all occurences of duplicates (LC-82)
public ListNode deleteDuplicates(ListNode head) {
if(head==null || head.next==null)return head;
ListNode dummy = new ListNode(0), curr = head, prev = dummy;
prev.next = curr;
while(curr != null) {
while (curr.next != null && curr.val == curr.next.val) {
curr = curr.next; //while loop to find the last node of the dups.
}
if (prev.next != curr) { //duplicates detected.
prev.next = curr.next; //remove the dups.
curr = curr.next; //reposition the curr pointer.
} else { //no dup, move down both pointer.
prev = prev.next;
curr = curr.next;
}
}
return dummy.next;
}
--------------------------------------------------------------------------------------------------------
10. Remove duplicates from Unsorted List O(N) S(N)
//Don't use Hashmap it will give TLE
public Node removeDuplicates(Node head)
{
Set<Integer>set=new HashSet<>();
Node prev= null;
Node curr= head;
while(curr!=null){
if(!set.contains(curr.data)){
set.add(curr.data);
prev=curr;
curr=curr.next;
}else{
curr=curr.next;
prev.next=curr;
}
}
return head;
}
--------------------------------------------------------------------------------------------------------
11. Intersection point in two linked list
Intuition->
a--> o-o-o-o-o
\
o-o-o
/
b--> o-o-o
->Suppose there are two sprinters 'b' started with startline whereas 'a' before startline(eg 2km behind the startline) now they start running and at some time refree see that this is unfair so he let 'b' first finish the race so when 'b' reaches end 'a' is exactly the diff(a-b) behind him. now refree let 'b' to cover the extra 2km distance by starting running from 'a's start point. in the mean time 'a' reaches to the end. at this position both start with exact same place. when we put 'a' at 'b's start point.
if (distA=distB) then 1 traversal.
if (distA!=distB) then 2 traversal.
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode first=headA;
ListNode second=headB;
while(first!=second){
first=(first==null)?headB:first.next;
second=(second==null)?headA:second.next;
}
return first;
}
--------------------------------------------------------------------------------------------------------
12. Intersection elements of 2 sorted linked list
public static Node findIntersection(Node head1, Node head2)
{
Node dummy = new Node(0);
Node head=dummy;
while(head1!=null&&head2!=null){
if(head1.data<head2.data){
head1=head1.next;
}else if(head1.data>head2.data){
head2=head2.next;
}else{
dummy=addToLast(dummy,head1.data);
head1=head1.next;
head2=head2.next;
}
}
head=head.next; //as first element is 0 in dummy;
return head;
}
public static Node addToLast(Node head,int val){
Node nn=new Node(val);
head.next=nn;
return nn;
}
--------------------------------------------------------------------------------------------------------
13. MergeSort LinkedList O(nLogn) S(1)
public ListNode MergeSort(ListNode head){
if(head==null||head.next==null){
return head;
}
ListNode mid=midNode(head);
ListNode nhead=mid.next;
mid.next=null;
ListNode fh=MergeSort(head);
ListNode sh=MergeSort(nhead);
return MergeLL(fh,sh);
}
public ListNode midNode(ListNode head){
ListNode fast= head;
ListNode slow= head;
while(fast.next!=null && fast.next.next!=null){
slow=slow.next;
fast=fast.next.next;
}
return slow;
}
//Merge Sort in constant Space complexity
public ListNode MergeLL(ListNode l1,ListNode l2){
ListNode dummy=new ListNode(0);
ListNode prev=dummy;
while(l1!=null && l2!=null){
if(l1.val<l2.val){
prev.next=l1;
l1=l1.next;
}else{
prev.next=l2;
l2=l2.next;
}
prev=prev.next;
}
prev.next=(l1!=null)?l1:l2;
return dummy.next;
}
--------------------------------------------------------------------------------------------------------
14. check for palindrome
public boolean isPalindrome(ListNode head) {
if(head==null||head.next==null){
return true;
}
ListNode slow=head;
ListNode fast=head;
while(fast.next!=null && fast.next.next!=null){
slow=slow.next;
fast=fast.next.next;
}
//reverse the right half
slow.next=reverseLL(slow.next);
slow=slow.next;
ListNode dummy=head;
while(slow!=null){
if(dummy.val!=slow.val){
return false;
}
slow=slow.next;
dummy=dummy.next;
}
return true;
}
--------------------------------------------------------------------------------------------------------
15. Odd Even Linked List
public ListNode oddEvenList(ListNode head) {
ListNode odd=new ListNode(0);
ListNode even=new ListNode(0);
ListNode evenT=even;
ListNode oddT=odd;
ListNode curr=head;
int i=1;
while(curr!=null){
if(i%2==0){
evenT.next=curr;
evenT=evenT.next;
}else{
oddT.next=curr;
oddT=oddT.next;
}
curr=curr.next;
i++;
}
oddT.next=even.next;
evenT.next=null;
return odd.next;
}
--------------------------------------------------------------------------------------------------------
15. Copy List With Random Pointer.
-> Firstly you should know about
Deep copy-> suppose we have some data in google drive and we gave it to someone he downloaded it and then make changes in it, these changes will not reflect in others.(New address)
Shallow copy->suppose the person have given the link of google drive, now any of the two if make some changes then it would reflect in the original one.(Same address)
->In this Question we have to make a deep copy of the given linked list
Approach 1) O(N)-S(N)->https://www.youtube.com/watch?v=deaZgauZVco
public Node copyRandomList(Node head) {
HashMap<Node,Node>map=new HashMap<>();
Node nHead=new Node(0);
Node prev=nHead;
Node curr=head;
while(curr!=null){
Node nn=new Node(curr.val);
prev.next=nn;
map.put(curr,nn);
curr=curr.next;
prev=prev.next;
}
nHead=nHead.next;
Node c1=head;
Node c2=nHead;
while(c1!=null){
c2.random=(c1.random!=null)?(map.get(c1.random)):null;
c1=c1.next;
c2=c2.next;
}
return nHead;
}
Approach 2) O(N)-S(1)->https://www.youtube.com/watch?v=VNf6VynfpdM
public Node copyRandomList(Node head) {
Node itr=head;
Node front=head;
// First round: make copy of each node,
// and link them together side-by-side in a single list.
while(itr!=null){
front =itr.next;
Node nn=new Node(itr.val);
itr.next=nn;
nn.next=front;
itr=front;
}
// Second round: assign random pointers for the copy nodes.
itr=head;
while(itr!=null){
if(itr.random!=null){
itr.next.random=itr.random.next;
}
itr=itr.next.next;
}
// Third round: restore the original list, and extract the copy list.
Node pseudoHead=new Node(0);
itr=head;
Node copy=pseudoHead;
while(itr!=null){
front=itr.next.next;
//extract the copy
copy.next=itr.next;
copy=copy.next;
//restore the original list
itr.next=front;
itr=front;
}
return pseudoHead.next;
}
--------------------------------------------------------------------------------------------------------
16. Remove Nth Node from last
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head.next==null){
return null;
}
ListNode fast=head;
for(int i=0;i<n;i++){
fast=fast.next;
}
ListNode dummy=new ListNode(0);
ListNode prev=dummy;
dummy.next=head;
ListNode slow=head;
while(fast!=null){
prev=slow;
fast=fast.next;
slow=slow.next;
}
prev.next=slow.next;
return dummy.next;
}
--------------------------------------------------------------------------------------------------------
17. Split list to parts
public ListNode[] splitListToParts(ListNode root, int k) {
ListNode[]result=new ListNode[k];
if(root==null){
return result;
}
int length=0;
ListNode temp=root;
while(temp!=null){
temp=temp.next;
length++;
}
int eachlength=length/k;
int extralength=length%k;
int index=0;
ListNode curr=root;
while(curr!=null){
ListNode head=curr;
int diff=(extralength<=0)?0:1; //as we are using this extra length to divide it evenly
//so we need to give each part only 1 extra length
for(int i=0;i<eachlength+diff-1;i++)
curr=curr.next;
ListNode xyz=curr.next;
curr.next=null;
curr=xyz;
result[index++]=head;
extralength--;
}
return result;
}
--------------------------------------------------------------------------------------------------------
18. Flattening a Linked List
->intuition=>we simply flatten the last two using mergeLL function and the resultant would be flatten with current second last. and so on
Node flatten(Node root)
{
if(root==null||root.next==null){
return root;
}
root.next=flatten(root.next);
//second last , last and so on
root= mergeLL(root,root.next);
return root;
}
Node mergeLL(Node a,Node b){
Node temp=new Node(0);
Node res=temp;
while(a!=null && b!=null){
if(a.data<b.data){
temp.bottom=a;
temp=temp.bottom;
a=a.bottom;
}else{
temp.bottom=b;
temp=temp.bottom;
b=b.bottom;
}
}
if(a!=null)temp.bottom=a;
else temp.bottom=b;
return res.bottom;
}
--------------------------------------------------------------------------------------------------------
19. First Non-repeating character in a stream.
public String FirstNonRepeating(String A)
{
StringBuilder str=new StringBuilder();
Queue<Character> q = new LinkedList<>();
int[] arr = new int[26];
for (int i = 0; i < A.length(); i++) {
char ch = A.charAt(i);
q.add(ch);
arr[ch - 'a']++;
while (!q.isEmpty()) {
if (arr[q.peek() - 'a'] > 1)
q.remove();
else
break;
}
if (q.isEmpty()) {
str.append("#");
} else {
str.append(q.peek());
}
}
return str.toString();
}
--------------------------------------------------------------------------------------------------------
20. Reorder List (Fold List) in constant space
Node reorderlist(Node head) {
if(head==null||head.next==null){
return head;
}
Node slow=head;
Node fast=head;
while(fast.next!=null && fast.next.next!=null){
slow=slow.next;
fast=fast.next.next;
}
//reverse the right half
Node head2=reverseLL(slow.next);
slow.next=null;
Node head1=head;
Node dummy=new Node(0);
Node prev=dummy;
int i=0;
while(head1!=null || head2!=null){
if(i%2==0){
if(head1!=null){
prev.next=head1;
head1=head1.next;
prev=prev.next;
}
}else{
if(head2!=null){
prev.next=head2;
head2=head2.next;
prev=prev.next;
}
}
i++;
}
return dummy.next;
}
--------------------------------------------------------------------------------------------------------
21. Merge K sorted Lists
Approach 1)Divide & Conquer -O(nkLogk)
public ListNode mergeKSortedLists(ListNode[]list,int si,int ei){
if(si>ei){
return null;
}
if(si==ei){
return list[si];
}
int mid=(si+ei)/2;
ListNode fh=mergeKSortedLists(list,si,mid);
ListNode sh=mergeKSortedLists(list,mid+1,ei);
return merge2lists(fh,sh);
}
Approach 2) Priority Queue - O(nkLogk),S(K)
public ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode>pq=new PriorityQueue<>((a,b)->(a.val-b.val));
for(ListNode l:lists){
if(l!=null)
pq.add(l);
}
ListNode dummy=new ListNode(0);
ListNode prev=dummy;
while(!pq.isEmpty()){
ListNode rn=pq.remove();
prev.next=rn;
prev=prev.next;
rn=rn.next;
if(rn!=null){
pq.add(rn);
}
}
prev.next=null;
return dummy.next;
}
--------------------------------------------------------------------------------------------------------
22. Multiply 2 LinkedLists
//Just Dry run normal Mulitplication for better understanding
public static ListNode multiplyTwoLL(ListNode l1, ListNode l2) {
l1=reverseLL(l1);
l2=reverseLL(l2);
ListNode dummy=new ListNode(-1);
ListNode ans_itr=dummy;
ListNode l2_itr=l2;
while(l2_itr!=null){
ListNode pro=multiplyLLwithDigit(l1,l2_itr.val);
l2_itr=l2_itr.next;
addTwoLL(pro,ans_itr);
ans_itr=ans_itr.next;
}
return reverseLL(dummy.next);
}
public static ListNode multiplyLLwithDigit(ListNode l1,int dig){
ListNode dummy=new ListNode(-1);
ListNode ac=dummy;
ListNode curr=l1;
int carry=0;
while(curr!=null||carry!=0){
int sum=carry+((curr!=null)?curr.val*dig:0);
int rem=sum%10;
carry=sum/10;
ac.next=new ListNode(rem);
if(curr!=null)
curr=curr.next;
ac=ac.next;
}
return dummy.next;
}
public static void addTwoLL(ListNode head,ListNode ansItr){
ListNode c1=head; //the list to be added with
ListNode c2=ansItr; //the resultant list of the previous mulitplication
//since c1 can be greater than or equal to c2(ansItr) so just checking for c1 condition only
int carry=0;
while(c1!=null||carry!=0){
int sum=carry+(c1!=null?c1.val:0) + (c2.next!=null?c2.next.val:0);
int rem=sum%10;
carry=sum/10;
if(c2.next!=null)c2.next.val=rem;
else c2.next=new ListNode(rem);
if(c1!=null)c1=c1.next;
c2=c2.next;
}
}
public static ListNode reverseLL(ListNode head){
if(head==null||head.next==null){
return head;
}
ListNode curr=head.next;
ListNode prev=head;
ListNode ahead;
while(curr!=null){
ahead=curr.next;
curr.next=prev;
prev=curr;
curr=ahead;
}
ListNode temp=head;
head=prev;
temp.next=null;
return head;
}
--------------------------------------------------------------------------------------------------------
23. Reverse a Doubly Linked List
Logic-> just reverse the linked list using next pointers.
and then take it as head and reverse again using prev pointers
--------------------------------------------------------------------------------------------------------
24. Find pairs with a given sum in a DLL
static void pairSum(Node head, int x) {
Node first = head;
Node second = head;
while (second.next != null)
second = second.next;
// To track if we find a pair or not
boolean found = false;
while (first != second && second.next != first) {
if ((first.data + second.data) == x) {
found = true;
System.out.println("(" + first.data + ", " + second.data + ")");
first = first.next;
second = second.prev;