-
-
Save schatterjee4/0142b671d59b3487e132676637a2f4bd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Node InsertNth(Node head, int data, int position) { | |
if(position == 0){ | |
Node node = new Node(); | |
node.data = data; | |
node.next = head; | |
return node; | |
} | |
head.next = InsertNth(head.next, data, position-1); | |
return head; | |
} | |
Node Delete(Node head, int position) { | |
if(position == 0){ | |
return head.next; | |
} | |
head.next = Delete(head.next, position-1); | |
return head; | |
} | |
void ReversePrint(Node head) { | |
if(head == null){ | |
return; | |
} | |
ReversePrint(head.next); | |
System.out.println(head.data); | |
} | |
int CompareLists(Node headA, Node headB) { | |
if (headA == null && headB == null){ | |
return 1; | |
} | |
else if (headA == null || headB == null){ | |
return 0; | |
} | |
return ((headA.data == headB.data)? 1: 0) & CompareLists(headA.next, headB.next); | |
} | |
//Merge two sorted linked lists | |
Node mergeLists(Node headA, Node headB) { | |
if(headA == null & headB ==null) | |
return null; | |
else if(headA == null) | |
return headB; | |
else if(headB == null) | |
return headA; | |
if(headA.data <= headB.data){ | |
headA.next = mergeLists(headA.next, headB); | |
} | |
else{ | |
Node temp = headB; | |
headB = headB.next; | |
temp.next = headA; | |
headA = temp; | |
headA.next = mergeLists(headA.next, headB); | |
} | |
return headA; | |
} | |
//find mid element of the linked list in one pass using Floyd cycle detection algorithm | |
private int findMiddleElement() { | |
if (head == null) | |
return -1; // return -1 for empty linked list | |
Node temp = head; | |
Node oneHop, twoHop; | |
oneHop = twoHop = temp; | |
while (twoHop != null && twoHop.next != null) { | |
oneHop = oneHop.next; | |
twoHop = twoHop.next.next; | |
} | |
return oneHop.data; | |
} | |
//Linkedlist loop detection | |
int detectAndRemoveLoop(Node node) { | |
Node slow = node, fast = node; | |
while (slow != null && fast != null && fast.next != null) { | |
slow = slow.next; | |
fast = fast.next.next; | |
// If slow and fast meet at same point then loop is present | |
if (slow == fast) { | |
removeLoop(slow, node); | |
return 1; | |
} | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment