'Folding a linked list using a Stack

Here is my program to fold a linked list using a Stack:

    public Node middle(Node head) {
            Node slow = head;
            Node fast = head;
            while (fast != null && fast.next != null) {
                fast = fast.next.next;
                slow = slow.next;
            }
            return slow;
        }

        public Node foldList(Node head){
            Node mid = middle(head);
            Node f = mid.next;
            Stack<Node> stacks = new Stack<>();
            if (head == null) return head;
            while (f != null){
                stacks.push(f);
                f = f.next;
            }
            Node temp = head;
            Node forv = head.next;
            while(!stacks.isEmpty()) {
                temp.next = stacks.pop();
                temp = temp.next;
                temp.next = forv;
                temp = temp.next;
                forv = forv.next;
            }
            return head;
        }

Here is the code of the middle() and foldList() methods. When I run it it gets stuck in an infinite loop. Can anybody help me find out why this is happening?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source