From 8f5a91a28462e01507fb0eeeb8dc005b572e9efd Mon Sep 17 00:00:00 2001 From: ayush26sharma <58669560+ayush26sharma@users.noreply.github.com> Date: Fri, 29 Oct 2021 11:08:08 +0530 Subject: [PATCH] Added some useful functions for singly linked list. Added three functions in total for singly linked list: 1. reverseList- basically the reverse list from a given position in the list till the end. a->b->c->d->e->f reverseList(c) a->b->f->e->d->c 2. detectLoop - It detects the loop in a given singly linked list using Floyd's tortoise and hare algorithm. a->b->c->d->e->f->g->h->c linkedlist.detectLoop() gives true in this case. 3. swapNodes - It simply swaps the two given nodes themselves and not just their data. (In place swapping) a->b->c->d->e->f swapNodes(b,e) a->e->c->d->b->f --- DataStructures/Lists/SinglyLinkedList.java | 59 +++++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) diff --git a/DataStructures/Lists/SinglyLinkedList.java b/DataStructures/Lists/SinglyLinkedList.java index 7e7b6166948f..2457bb3a6376 100644 --- a/DataStructures/Lists/SinglyLinkedList.java +++ b/DataStructures/Lists/SinglyLinkedList.java @@ -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);