File tree 2 files changed +49
-0
lines changed
src/main/java/com/thealgorithms/datastructures
2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change @@ -56,6 +56,54 @@ public boolean detectLoop() {
56
56
return flag ;
57
57
}
58
58
59
+ /**
60
+ * Swaps nodes of two given values a and b.
61
+ *
62
+ */
63
+ public void swapNodes (int valueFirst , int valueSecond ) {
64
+ if (valueFirst == valueSecond ){
65
+ return ;
66
+ }
67
+ Node previousA = null ,currentA = head ;
68
+ while (currentA != null && currentA .value != valueFirst ){
69
+ previousA = currentA ;
70
+ currentA = currentA .next ;
71
+ }
72
+
73
+ Node previousB = null ,currentB = head ;
74
+ while (currentB != null && currentB .value != valueSecond ){
75
+ previousB = currentB ;
76
+ currentB = currentB .next ;
77
+ }
78
+ /** If either of 'a' or 'b' is not present, then return */
79
+ if (currentA == null || currentB == null ){
80
+ return ;
81
+ }
82
+
83
+ // If 'a' is not head node of list
84
+ if (previousA != null ){
85
+ previousA .next = currentB ;
86
+ }
87
+ else {
88
+ // make 'b' as the new head
89
+ head = currentB ;
90
+ }
91
+
92
+ // If 'b' is not head node of list
93
+ if (previousB != null ){
94
+ previousB .next = currentA ;
95
+ }
96
+ else {
97
+ // Make 'a' as new head
98
+ head = currentA ;
99
+ }
100
+ // Swap next pointer
101
+
102
+ Node temp = currentA .next ;
103
+ currentA .next = currentB .next ;
104
+ currentB .next = temp ;
105
+ }
106
+
59
107
/**
60
108
* Reverse a singly linked list from a given node till the end
61
109
*
Original file line number Diff line number Diff line change @@ -38,6 +38,7 @@ public static void main(String[] args) throws Exception {
38
38
Scanner sc = new Scanner (System .in );
39
39
String str = sc .nextLine ();
40
40
System .out .println (check (str ));
41
+ sc .close ();
41
42
}
42
43
43
44
}
You can’t perform that action at this time.
0 commit comments