Java实现反转链表(递归)

发布于 2021-07-22  64 次阅读


在单链表类后面新增 void reverse()和 Node reverse(Node p)方法

代码如下:

package com.apesblog.ReverseLinkList1;

import java.util.Iterator;

import javax.swing.text.html.HTMLDocument.HTMLReader.PreAction;

public class ReverseLinkList1<T> implements Iterable<T> {
    private Node head;
    private int N;

    private class Node {
        private T item;
        private Node next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }

    public ReverseLinkList1() {
        this.head = new Node(null, null);
        N = 0;
    }

    public T get(int i) {
        if (i < 1 || i > N) {
            throw new RuntimeException("查询位置不正确");
        }
        Node p = head;
        for (int index = 1; index <= i; index++) {
            p = p.next;
        }
        return p.item;
    }

    public void add(T t) {
        Node p = head;
        while (p.next != null) {
            p = p.next;
        }
        p.next = new Node(t, null);
        N++;
    }

    public void insert(int i, T t) {
        if (i < 1 || i >= N) {
            throw new RuntimeException("插入位置不正确");
        }
        Node p = head;
        for (int index = 1; index < i; index++) {
            p = p.next;
        }
        p.next = new Node(t, p.next);
        N++;
    }

    public void delete(int i) {
        if (i < 1 || i > N) {
            throw new RuntimeException("删除位置不正确");
        }
        Node p = head;
        for (int index = 1; index < i; index++) {
            p = p.next;
        }
        p.next = p.next.next;
        N--;
    }

    public void reverse() {
        Node p = head;
        reverse(p.next);
    }

    private Node reverse(Node p) {
        if (p.next == null) {
            head.next = p;
            return p;
        }
        Node per = reverse(p.next);
        per.next = p;
        p.next = null;
        return p;
    }

    @Override
    public Iterator<T> iterator() {

        return new Iterator() {
            private Node p = head;

            @Override
            public boolean hasNext() {
                return p.next != null;
            }

            @Override
            public Object next() {
                p = p.next;
                return p.item;
            }

        };
    }

}

测试类代码如下:

package com.apesblog.ReverseLinkList1;

public class Test {

    public static void main(String[] args) {
        ReverseLinkList1<String> l = new ReverseLinkList1<String>();
        l.add("1");
        l.add("2");
        l.add("3");
        l.add("4");

        StringBuilder str = new StringBuilder(300);
        str.append("遍历:");
        for (String s : l) {
            str.append(s + " ");
        }
        System.out.println(str);

        l.reverse();
        str.delete(0, str.length());
        str.append("反转:");
        for (String s : l) {
            str.append(s + " ");
        }
        System.out.println(str);

    }

}

运行结果如下: