@@ -20,35 +20,47 @@ private GaleShapley() {
20
20
* @param menPrefs A map containing men's preferences where each key is a man and the value is an array of women in order of preference.
21
21
* @return A map containing stable matches where the key is a woman and the value is her matched man.
22
22
*/
23
- public static Map <String , String > stableMatch (Map <String , LinkedList <String >> womenPrefs , Map < String , LinkedList < String >> menPrefs ) {
24
- // Initialize all men as free
23
+ public static Map <String , String > stableMatch (Map <String , LinkedList <String >> womenPrefs ,
24
+ Map < String , LinkedList < String >> menPrefs ) {
25
25
Map <String , String > engagements = new HashMap <>();
26
- LinkedList <String > freeMen = new LinkedList <>(menPrefs .keySet ());
26
+ Queue <String > freeMen = new LinkedList <>(menPrefs .keySet ());
27
27
28
- // While there are free men
29
28
while (!freeMen .isEmpty ()) {
30
- String man = freeMen .poll (); // Get the first free man
31
- LinkedList <String > manPref = menPrefs .get (man ); // Get the preferences of the man
29
+ String man = freeMen .poll ();
30
+ LinkedList <String > manPref = menPrefs .get (man );
31
+
32
+ // Ensure manPref is not null before proceeding
33
+ if (manPref == null ) {
34
+ continue ;
35
+ }
32
36
33
37
// Propose to the first woman in the man's preference list
34
38
String woman = manPref .poll ();
35
39
String fiance = engagements .get (woman );
36
40
37
- // If the woman is not engaged, engage her with the current man
38
41
if (fiance == null ) {
42
+ // Woman is free, engage the man and woman
39
43
engagements .put (woman , man );
40
44
} else {
41
- // If the woman prefers the current man over her current fiance
45
+ // Woman is already engaged, check if she prefers this man over her current fiance
42
46
LinkedList <String > womanPrefList = womenPrefs .get (woman );
47
+
48
+ // Ensure womanPrefList is not null before comparing
49
+ if (womanPrefList == null ) {
50
+ continue ;
51
+ }
52
+
53
+ // If the woman prefers the current man over her current fiance
43
54
if (womanPrefList .indexOf (man ) < womanPrefList .indexOf (fiance )) {
44
55
engagements .put (woman , man );
45
56
freeMen .add (fiance ); // Previous fiance becomes free
46
57
} else {
47
- // Woman rejects the new proposal, the man remains free
58
+ // Woman stays with her current fiance, man remains free
48
59
freeMen .add (man );
49
60
}
50
61
}
51
62
}
52
- return engagements ; // Return the stable matches
63
+
64
+ return engagements ;
53
65
}
54
66
}
0 commit comments