Advertisement
Ham62

Reversing Linked List

Apr 6th, 2019
525
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.86 KB | None | 0 0
  1. global IntNode head
  2.  
  3.   // Correct solution  
  4.   public void reverse() {
  5.     if (head == null)
  6.       return;
  7.    
  8.     head = reverseOrder(head);
  9.   }
  10.  
  11.   static IntNode reverseOrder(IntNode start) {
  12.     IntNode nextNode = start.getLink();
  13.     if (nextNode == null)
  14.       return start;
  15.  
  16.     IntNode newHead = reverseOrder(nextNode);
  17.     nextNode.setLink(start);
  18.     start.setLink(null);
  19.    
  20.     return newHead;
  21.   }
  22.  
  23.   // incorrect solution
  24.   public void reverse() {
  25.     if (head == null)
  26.       return;
  27.    
  28.     IntNode tail = reverseOrder(head);
  29.     tail.setLink(null);
  30.   }
  31.  
  32.   IntNode reverseOrder(IntNode start) {
  33.     if (start.getLink() != null) {
  34.       IntNode newHead = reverseOrder(start.getLink());
  35.       newHead.setLink(start);
  36.       return start;
  37.     }
  38.    
  39.     System.out.println("e");
  40.     head = start;
  41.     return start;
  42.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement