Modify singly linked list swap function to swap nodes (#2983)

This commit is contained in:
RishabhSrivastava1423 2022-03-27 01:01:11 +05:30 committed by GitHub
parent 7d5de041eb
commit d53c2cef8c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 49 additions and 0 deletions

View File

@ -56,6 +56,54 @@ public class SinglyLinkedList extends Node{
return flag;
}
/**
* Swaps nodes of two given values a and b.
*
*/
public void swapNodes(int valueFirst, int valueSecond) {
if(valueFirst == valueSecond){
return;
}
Node previousA = null ,currentA = head;
while(currentA != null && currentA.value != valueFirst){
previousA = currentA;
currentA = currentA.next;
}
Node previousB = null ,currentB = head;
while(currentB != null && currentB.value != valueSecond){
previousB = currentB;
currentB = currentB.next;
}
/** If either of 'a' or 'b' is not present, then return */
if(currentA == null || currentB == null){
return;
}
// If 'a' is not head node of list
if(previousA != null){
previousA.next = currentB;
}
else{
// make 'b' as the new head
head = currentB;
}
// If 'b' is not head node of list
if(previousB != null){
previousB.next = currentA;
}
else{
// Make 'a' as new head
head = currentA;
}
// Swap next pointer
Node temp = currentA.next;
currentA.next = currentB.next;
currentB.next = temp;
}
/**
* Reverse a singly linked list from a given node till the end
*

View File

@ -38,6 +38,7 @@ public class DuplicateBrackets {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(check(str));
sc.close();
}
}