JAVA实现反转链表

public class ListNodeTest {
    private static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }


        public String show() {
           return this.val + "->" + (this.next == null ? "NULL" : this.next.show());
        }
    }


    /**
     * 迭代
     */
    public ListNode reverseList2(ListNode head) {
        ListNode pre = null;                  //存上一个节点
        while (head != null) {
            ListNode current = head;
            head = head.next;
            current.next = pre;
            pre = current;
        }
        return pre;
    }

    /**
     * 递归
     */
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode nextNode = head.next;
        ListNode newHead = reverseList(nextNode);
        nextNode.next = head;
        head.next = null;
        return newHead;
    }

    @Test
    public void testReverse() {
        ListNode a = new ListNode(1);
        ListNode b = new ListNode(2);
        ListNode c = new ListNode(3);
        ListNode d = new ListNode(4);

        a.next = b;
        b.next = c;
        c.next = d;

        System.out.println(a.show());

        System.out.println(reverseList2(a).show());
    }

}

你可能感兴趣的:(算法学习,java基础)