反转链表

public class Demo1 {
    Node head;
    Node last;
    int size;

    // 构造链表
    void buildList() {
        head = new Node(1, null);
        size++;
        Node curentNode = head;
        for (int i = 2; i < 10; i++) {
            Node node = new Node(i, null);
            curentNode.setNext(node);
            curentNode = curentNode.next;
            if (i == 9) {
                last = node;
            }
            size++;
        }
    }

    public static void main(String[] args) {
        Demo1 demo1 = new Demo1();
        demo1.reverseListNode();
        demo1.reverseListNode02();
    }

    // 反转链表
    public void reverseListNode() {
        buildList();
        if (head == null) {
            return;
        } else {
            Node node = doReverseListNode(head);
            last = node;
            System.out.println(node);
        }
    }

    // 反转链表2
    public void reverseListNode02() {
        buildList();
        Node node = head;
        Node prev = null;
        while (node != null) {
            Node next = node.next;
            // 到最后一个元素了
            node.next = prev;
            prev = node;
            node = next;
        }
        last = head;
        head = prev;
    }

    private Node doReverseListNode(Node node) {
        Node next = node.next;
        if (next == null) {
            head.next = null;
            Node head = new Node(node.data, next);
            this.head = head;
            return head;
        }
        Node node1 = doReverseListNode(next);
        node1.next = node;
        return node;
    }

    private static class Node {
        int data;
        Node next;

        public Node(int data, Node next) {
            this.data = data;
            this.next = next;
        }

        public int getData() {
            return data;
        }

        public void setData(int data) {
            this.data = data;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容