反转链表

思路:

 一开始需要将pre的next置空

代码:

public class Client {


    public static void main(String[] args) {
        ListNode listNode = initNode();
        System.out.println();

        reverNode(listNode);
    }

    private static void reverNode(ListNode head) {
        ListNode first = null;
        ListNode pre = head;
        ListNode next = head.next;
        pre.next = null;
        while (next != null) {
            first = next;
            ListNode nextNext = next.next;
            next.next = pre;
            pre = next;
            next = nextNext;
        }

        System.out.println(first);

    }

    private static ListNode initNode() {
        ListNode root = new ListNode(0);
        ListNode pre = root;
        for (int i = 1; i < 3; i++) {
            ListNode node = new ListNode(i);
            pre.next = node;
            pre = node;
        }
        return root;
    }

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

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
原文地址:https://www.cnblogs.com/dongma/p/14197429.html