Skip to content

Commit

Permalink
reverse data using heap mover
Browse files Browse the repository at this point in the history
  • Loading branch information
abhinav12k committed Jun 7, 2020
1 parent 16a32d8 commit a12abd7
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 10 deletions.
88 changes: 78 additions & 10 deletions LinkedList/LinkedList.java
Original file line number Diff line number Diff line change
Expand Up @@ -233,24 +233,92 @@ public void reverseDataIteratively() throws Exception {
}

public void reversePointerIteratively() {

Node prev = head;
Node curr = head.next;
while(curr!=null) {

while (curr != null) {

Node ahead = curr.next;
curr.next = prev;
prev=curr;
curr=ahead;

prev = curr;
curr = ahead;
}

Node temp = head;
head = tail;
tail = temp;
tail.next = null;


}

public void RPR() {

reversePointerRecursively(head, head.next);
Node temp = head;
head = tail;
tail = temp;
tail.next = null;

}

private void reversePointerRecursively(Node prev, Node curr) {

if (curr == null) {
return;
}

reversePointerRecursively(curr, curr.next);
curr.next = prev;
}

public void RDR() {
reverseDataRecursively(head, head, 0);
}


private Node reverseDataRecursively(Node left, Node right, int count) {

if (right == null) {
return left;
}

Node ln = reverseDataRecursively(left, right.next, count + 1);

if (count >= size / 2) {
int temp = ln.data;
ln.data = right.data;
right.data = temp;
}

return ln.next;
}

public void RDRHeap() {
Heapmover hp = new Heapmover();
hp.left = head;
ReverseDataRecursivelyHeap(hp, head, 0);
}

public class Heapmover {
public Node left;
}

private void ReverseDataRecursivelyHeap(Heapmover hp, Node right, int count) {

if (right == null) {
return;
}

ReverseDataRecursivelyHeap(hp, right.next, count + 1);

if (count >= size / 2) {
int temp = hp.left.data;
hp.left.data = right.data;
right.data = temp;
}

hp.left = hp.left.next;
}

}
8 changes: 8 additions & 0 deletions LinkedList/LinkedListClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ public static void main(String[] args) throws Exception {
ll.reversePointerIteratively();
ll.display();

ll.RPR();
ll.display();

ll.RDR();
ll.display();

ll.RDRHeap();
ll.display();
}

}

0 comments on commit a12abd7

Please sign in to comment.