fork(1) download
  1. /**
  2.  * Folding LInked List
  3.  * @author PRATEEK
  4.  */
  5. class FoldList {
  6.  
  7. static Node foldList(Node head)
  8. {
  9. return fold(head,head);
  10. }
  11.  
  12. private static Node fold(Node head, Node curr) {
  13. if (curr == null)
  14. return head;
  15.  
  16. Node result = fold(head, curr.next);
  17.  
  18. // condition to stop execution if result is head and curr is not the
  19. // last node
  20. if (result != head || curr.next == null)
  21. {
  22. // handling odd and even number of nodes
  23. if (result != curr && result.next!=curr)
  24. {
  25. curr.next = result.next;
  26. result.next = curr;
  27. return curr.next;
  28. }
  29. curr.next = null;
  30. }
  31. return head;
  32. }
  33.  
  34. public static void displayList(Node head) {
  35. Node tempNode;
  36. tempNode = head;
  37. while (tempNode != null) {
  38. System.out.print(tempNode.data + "-->");
  39. tempNode = tempNode.next;
  40. }
  41. System.out.print("null");
  42. System.out.println();
  43. }
  44.  
  45. public static void main(String[] args) {
  46. Node root = new Node(1);
  47. root.next = new Node(2);
  48. root.next.next = new Node(3);
  49. root.next.next.next = new Node(4);
  50. root.next.next.next.next = new Node(5);
  51. root.next.next.next.next.next = new Node(6);
  52. root.next.next.next.next.next.next = new Node(7);
  53. displayList(root);
  54. displayList(foldList(root));
  55.  
  56. }
  57. }
  58.  
  59. /**
  60.  * Linked List Node
  61.  * @author Prateek
  62.  */
  63. class Node {
  64.  
  65. public int data;
  66. public Node next;
  67. public Node prev;
  68.  
  69. public Node(int data) {
  70. this.data = data;
  71. }
  72.  
  73. public String toString() {
  74. return ""+this.data;
  75. }
  76. }
Success #stdin #stdout 0.07s 380160KB
stdin
Standard input is empty
stdout
1-->2-->3-->4-->5-->6-->7-->null
1-->7-->2-->6-->3-->5-->4-->null