Skip to content

Singly linked list swap function modified to swap nodes. #2983

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,54 @@ public boolean detectLoop() {
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
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(check(str));
sc.close();
}

}