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); }
/** * 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; }
public ListNode reverseList(ListNode head) { ListNode newHead = null; while (head != null) { ListNode next = head.next; head.next = newHead; newHead = head; head = next; } return newHead; }
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; }