为了账号安全,请及时绑定邮箱和手机立即绑定

我无法使用递归以相反的顺序打印链表元素

我无法使用递归以相反的顺序打印链表元素

冉冉说 2021-05-15 19:14:39
我是Java的初学者。我正在链表中实现递归以按相反的顺序打印元素,但我认为我的代码中存在语义错误,请提前检查我的代码(尤其是反向方法)。输出:78 30 52发送后,从头开始您需要插入包装练习的物品计数;public class Linkedlist {    Node head;    public Linkedlist() {        head = null;    }    public void insert(int data) {        Node obj1 = new Node(data);        obj1.next = head;        head = obj1;    }    public void append(int data) {        Node newn = new Node(data);        if (head == null) {            newn.next = null;            head = newn;            return;        }        Node n = head;        while (n.next != null) {            n = n.next;        }        newn.next = null;        n.next = newn;    }    void delete(int data) {        if (head == null) {            return;        } else if (head.data == data) {            head = head.next;            return;        }        Node curr = head;        while (curr.next != null) {            if (curr.next.data == data) {                curr.next = curr.next.next;            }            curr = curr.next;        }    }    void insertAt(int count, int data) {        Node h = head;        if (count == 0) {            this.insert(data);            return;        }        while (h.next != null) {            if (count == 0) {                Node f = new Node(data);                f = h.next;                h = f;                return;            }            count--;            h = h.next;        }    }    public void reverse() {        if (head == null) {            System.out.println("null");        } else {            this.reverseRecursive(head);        }    }    private void reverseRecursive(Node nod) {        if (nod == null) {            return;        }        reverseRecursive(nod.next);        System.out.print(nod.data + " ");    }    class Node {        Node next;        int data;        public Node(int data) {            this.data = data;        }    }
查看完整描述

2 回答

?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

在您的LinkedList中,而不是使用insert方法(该方法在头部添加一个元素),请使用append方法,该方法在LinkedList的末尾添加该元素,然后调用反向方法。


查看完整回答
反对 回复 2021-05-26
  • 2 回答
  • 0 关注
  • 125 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信