File tree 3 files changed +77
-1
lines changed
DataAndAlgoL/Chp3LinkedLists
LeetCode/Grind169/LinkedLists 3 files changed +77
-1
lines changed Original file line number Diff line number Diff line change
1
+ package DataAndAlgoL .Chp3LinkedLists ;
2
+ /*
3
+ * Josephus Circle: N people have decided to elect a leader by arranging themselves in a circle
4
+ * and eleminenting every Mth person arounf the circle, closing ranks as each person drops out
5
+ * Find which person will be the last one remaining with rank 1
6
+ *
7
+ * SOLUTION: Assume the input is a circular linked list with N nodes and each node has a number
8
+ * range 1 to N associated with it. Head node has number 1 as data.
9
+ */
10
+ public class Problem44 {
11
+ public static void main (String [] args ) {
12
+
13
+ }
14
+
15
+ public ListNode getJosephusPosition (int N , int M ){
16
+ ListNode p ;
17
+ ListNode q ;
18
+ //create circular linked list containing all the players
19
+ p .setData (1 );
20
+
21
+ q =p ;
22
+
23
+ for (int i =2 ; i <= N ; i ++){
24
+ p =p .getNext ();
25
+ p .setData (i );
26
+ }
27
+
28
+ p .setNext (q ); // Close the circular linked list by having the last node point to the first
29
+
30
+ for (int count =N ; count >1 ; count --){
31
+ for (int i =0 ; i <M -1 ; i ++){
32
+ p =p .getNext ();
33
+ p .setNext (p .getNext ().getNext ());// remove the eliminated player from the list
34
+ }
35
+ }
36
+
37
+ return p ;
38
+
39
+
40
+ }
41
+ }
Original file line number Diff line number Diff line change @@ -60,4 +60,4 @@ public static boolean isPalindrome(ListNode head) {
60
60
61
61
return true ;
62
62
}
63
- }
63
+ }
Original file line number Diff line number Diff line change
1
+ package Grind169 .LinkedLists ;
2
+
3
+ public class RemoveNthNodeFromEndList_19 {
4
+ public class ListNode {
5
+ int val ;
6
+ ListNode next ;
7
+ ListNode () {}
8
+ ListNode (int val ) { this .val = val ; }
9
+ ListNode (int val , ListNode next ) { this .val = val ; this .next = next ; }
10
+ }
11
+
12
+ public static void main (String [] args ) {
13
+
14
+ }
15
+
16
+ //USE FLOYED CYCLE ALGORITHM
17
+ public ListNode removeNthFromEnd (ListNode head , int n ) {
18
+ ListNode start = new ListNode (0 );
19
+ ListNode slow = start , fast = start ;
20
+ slow .next = head ;
21
+
22
+ //Move fast in front so that the gap between slow and fast becomes n
23
+ for (int i =1 ; i <=n +1 ; i ++) {
24
+ fast = fast .next ;
25
+ }
26
+ //Move fast to the end, maintaining the gap
27
+ while (fast != null ) {
28
+ slow = slow .next ;
29
+ fast = fast .next ;
30
+ }
31
+ //Skip the desired node
32
+ slow .next = slow .next .next ;
33
+ return start .next ;
34
+ }
35
+ }
You can’t perform that action at this time.
0 commit comments