Esempio n. 1
0
 public static void main(String[] args) {
   int[] A = new int[] {1, 2, 3, 4};
   ListNode head = ListNode.buildList(A);
   ReverseLinkedList rll = new ReverseLinkedList();
   ListNode ans = rll.reverseListRec(head);
   ListNode.printNode(ans);
 }
Esempio n. 2
0
 /**
  * My first implementation of iteration
  *
  * @param head
  * @return
  */
 public ListNode reverseListIte1st(ListNode head) {
   if (head == null) {
     return head;
   }
   ListNode tail = head;
   ListNode pre = new ListNode(0);
   ListNode post;
   while (head != null) {
     post = head.next;
     head.next = pre;
     pre = head;
     head = post;
   }
   tail.next = null;
   return pre;
 }
Esempio n. 3
0
 public ListNode reverseList(ListNode head) {
   ListNode newHead = null;
   while (head != null) {
     ListNode next = head.next;
     head.next = newHead;
     newHead = head;
     head = next;
   }
   return newHead;
 }
Esempio n. 4
0
 private ListNode helper(ListNode head) {
   if (head == null) {
     return head;
   }
   if (head.next == null) {
     return head;
   }
   ListNode newHead = helper(head.next);
   head.next.next = head;
   head.next = null;
   return newHead;
 }