From 194316cb6017af3d6f954e43c38b263439b1098e Mon Sep 17 00:00:00 2001 From: Kartick Gulati <68003347+kartickg33@users.noreply.github.com> Date: Wed, 28 Apr 2021 19:26:17 +0530 Subject: [PATCH] chore(Java): add fold-linked-list (#266) --- algorithms/Java/README.md | 1 + .../Java/linked-lists/fold-linked-list.java | 92 +++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 algorithms/Java/linked-lists/fold-linked-list.java diff --git a/algorithms/Java/README.md b/algorithms/Java/README.md index 63e316be..ef941e12 100644 --- a/algorithms/Java/README.md +++ b/algorithms/Java/README.md @@ -18,6 +18,7 @@ 3. [Doubly](linked-lists/doubly.java) 4. [Reverse](linked-lists/reverse.java) 5. [Singly](linked-lists/singly.java) +6. [Fold Linked List](linked-lists/fold-linked-list.java) ## Queues diff --git a/algorithms/Java/linked-lists/fold-linked-list.java b/algorithms/Java/linked-lists/fold-linked-list.java new file mode 100644 index 00000000..55b59962 --- /dev/null +++ b/algorithms/Java/linked-lists/fold-linked-list.java @@ -0,0 +1,92 @@ +// Java implementation for folding a linked list +public static class Node { + int data; + Node next; + public Node(int data){ + this.data = data; + this.next = null; + } +} + +public static class LinkedList { + Node head; + Node tail; + int size; + + public void display() { + for (Node temp = head; temp != null; temp = temp.next) { + System.out.print(temp.data + " "); + } + System.out.println(); + } + + public void addFirst(int val) { + Node temp = new Node(val); + temp.next = head; + head = temp; + if (size == 0) { + tail = temp; + } + size++; + } + + void addLast(int val) { + Node temp = new Node(val); + temp.next = null; + if (size == 0) { + head = tail = temp; + } else { + tail.next = temp; + tail = temp; + } + size++; + } + + Node fleft; + private void foldhelper(Node right , int floor){ + if(right == null){ + return; + } + foldhelper(right.next , floor+1); + if(floor>size/2){ + Node val = fleft.next; + fleft.next = right; + right.next = val; + fleft = val; + } + else if(floor==size/2){ + this.tail = right; + tail.next = null; + } + else{ + // do nothing + } + } + + public void fold() { + fleft = this.head; + foldhelper(this.head, 0); + } +} + +//Driver Code +public static void main(String[] args) throws Exception { + LinkedList ll = new LinkedList(); + int n = 6; + for (int i = 1; i <= n; i++) { + ll.addLast(i); + } + // LinkedList --> [1,2,3,4,5,6] for n = 6 + + System.out.print("Linked List before folding --> "); + ll.display(); + ll.fold(); + System.out.print("Linked List after folding --> "); + ll.display(); +} + +/* + Output:- + Linked List before folding --> 1 2 3 4 5 6 + Linked List after folding --> 1 6 2 5 3 4 +*/