Skip to content

Commit d53c2ce

Browse files
Modify singly linked list swap function to swap nodes (TheAlgorithms#2983)
1 parent 7d5de04 commit d53c2ce

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,54 @@ public boolean detectLoop() {
5656
return flag;
5757
}
5858

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+
59107
/**
60108
* Reverse a singly linked list from a given node till the end
61109
*

src/main/java/com/thealgorithms/datastructures/stacks/DuplicateBrackets.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ public static void main(String[] args) throws Exception {
3838
Scanner sc = new Scanner(System.in);
3939
String str = sc.nextLine();
4040
System.out.println(check(str));
41+
sc.close();
4142
}
4243

4344
}

0 commit comments

Comments
 (0)