leetcode-206-反转链表

问题:

package com.example.demo;

public class Test206 {

    /**
     * 翻转链表
     * 方法一:迭代
     * 思路:
     * 每次循环的时候交换两个节点
     *
     * @param head
     * @return
     */
    public ListNode reverseList(ListNode head) {
        // 构建一个新的链表
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            // 将当前处理节点的下一个节点暂存(也就是分开当前节点和下一个节点 2  3->4->5)
            ListNode next = cur.next;
            // 将当前节点赋给新链表 , 2->1
            cur.next = pre;
            // 重新覆盖新链表
            pre = cur;
            // 处理下一个节点
            cur = next;
        }
        return pre;
    }

    /**
     * 方法二:递归
     */
    public ListNode reverseList1(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode p = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return p;
    }


    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}
原文地址:https://www.cnblogs.com/nxzblogs/p/11276020.html