链表反转

基础算法练习:链表反转

/**
 * @author JH_Y
 * @version 1.0
 * 链表反转
 */
public class LinkedListInversion {
    /*
     * 将单链表的链接顺序反转过来
     * 例:输入:1->2->3->4->5
     * 输出:5->4->3->2->1
     * 使用两种方式解题
     */

    static class ListNode {
        int value;
        ListNode next;

        public ListNode(int value, ListNode next) {
            this.value = value;
            this.next = next;
        }

        // 便于看打印结果
        @Override
        public String toString() {
            return
                    "=> " + value +
                    "= " + next ;
        }


        // 便于理解
//        @Override
//        public String toString() {
//            return "ListNode{" +
//                    "value=" + value +
//                    ", next=" + next +
//                    '}';
//        }
    }

    /**
     * 迭代
     */
    public static ListNode iterate(ListNode head) {
        ListNode prev = null, next;
        ListNode curr = head;
        while (curr != null) {
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }

        return prev;
    }

    /**
     * 递归
     */

    public static ListNode recursive(ListNode head){

        if ( head==null || head.next==null){
            return head;
        }

        ListNode newNode = recursive(head.next);
        head.next.next = head;
        head.next = null;
        return newNode;
    }

    public static void main(String[] args) {

        ListNode node5 = new ListNode(5, null);
        ListNode node4 = new ListNode(4, node5);
        ListNode node3 = new ListNode(3, node4);
        ListNode node2 = new ListNode(2, node3);
        ListNode node1 = new ListNode(1, node2);
        System.out.println("链表原顺序:"+node1);
//        ListNode prev = iterate(node1);
//        System.out.println("反转链表顺序:"+prev);
        ListNode recursive = recursive(node1);
        System.out.println("递归反转顺序:"+recursive);
    }


}
上一篇:Leetcode#725. 分割链表


下一篇:leetcode解题思路分析(九十四)818 - 824 题