Skip to content

Added some useful functions for singly linked list. #2757

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 2 commits into from
Oct 30, 2021
Merged
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
59 changes: 58 additions & 1 deletion DataStructures/Lists/SinglyLinkedList.java
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,64 @@ public void insertNth(int data, int position) {
cur.next = newNode;
size++;
}


/**
Detects if there is a loop in the singly linked list
using floy'd turtle and hare algorithm.
**/
public boolean detectLoop(){
Node currentNodeFast = head;
Node currentNodeSlow = head;
boolean flag = false;
while(currentNodeFast!=null && currentNodeFast.next != null && currentNodeSlow!=null && currentNodeSlow.next != null){
currentNodeFast = currentNodeFast.next.next;
currentNodeSlow = currentNodeSlow.next;
if (currentNodeFast==currentNodeSlow){
flag = true;
break;
}
}
return flag;
}

/**
Swaps nodes of two given values a and b.
**/

public void swapNodes(int a, int b){
Node currentNode = head;
Node temp = null;
while(currentNode!=null){
if (currentNode.next.value == a){
temp = currentNode.next;
}
if(currentNode.next.value == b){
currentNode.next=temp;
}
currentNode=currentNode.next;
}
}


/**
Reverse a singly linked list from a given node till the end
**/


Node reverseList(Node node) {
Node prev = null, curr = node, next;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
node = prev;
return node;
}



/** Deletes a node at the head */
public void deleteHead() {
deleteNth(0);
Expand Down